Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing last comma in SELECT statement

Tags:

sql

sql-server

I have a select query which looks like this:

SELECT 
ROW_NUMBER() OVER (ORDER BY T.TitleId) as Row, 
T.TitleId as TitleID, 
T.TitleSort as TitleName, 
TT.Description as TitleType, 
TS.Description as TitleOrigin,
--get genres
(select Genre.Description + ', ' from Genre where GenreId IN
(Select GenreId from TitleGenre WHERE TitleId = T.TitleId)
group by Genre.Description for xml path('')) AS Genres, ....

This code works, but I can't find a way to get rid of the last comma. This is how the returned row looks:

Action, Drama, Romance, 

I need to get rid of last comma without using a function or declaring a variable, right here in the query. Is that possible? Thanks in advance for your answers.

like image 672
pnduke Avatar asked Jun 15 '26 10:06

pnduke


2 Answers

Something like this should be close -- basically move the comma to the beginning and then remove it with STUFF:

STUFF(
        (
        select ', ' + Genre.Description from Genre where GenreId IN
(Select GenreId from TitleGenre WHERE TitleId = T.TitleId)
group by Genre.Description for xml path('')
        ), 1, 2, '') 

Good luck.

like image 165
sgeddes Avatar answered Jun 17 '26 23:06

sgeddes


You can always use the following which uses Left() and Len():

select *,
  left(Genres, len(Genres)-1) as Genres
from 
(
  SELECT 
  ROW_NUMBER() OVER (ORDER BY T.TitleId) as Row, 
  T.TitleId as TitleID, 
  T.TitleSort as TitleName, 
  TT.Description as TitleType, 
  TS.Description as TitleOrigin,
  --get genres
  (select Genre.Description + ', ' from Genre where GenreId IN
  (Select GenreId from TitleGenre WHERE TitleId = T.TitleId)
  group by Genre.Description for xml path('')) AS Genres, ....
) src
like image 36
Taryn Avatar answered Jun 18 '26 00:06

Taryn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!