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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With