COALESCE with DISTINCT in SQLServer

June 3, 2010 at 11:58 am 8 comments

If you want comma separated values from columns it is so simple. Use COALESCE function provided by SQL Server.

DECLARE @csv varchar(max)
select @csv = COALESCE(@csv + ',','') + cast(id  AS VARCHAR) from tablename
print @csv

COALESCE with DISTINCT Values

If you want, DISTINCT values in COALESCE function use inner table like below.

DECLARE @csv varchar(max)
select @csv = COALESCE(@csv + ',','') + cast(id  AS VARCHAR) from
(SELECT DISTINCT id FROM TableName)
print @csv

Happy Programming 😉

Entry filed under: SQL Server. Tags: , , , .

Decode html through javascript How to expire(remove) page caching in ASP.Net

8 Comments Add your own

  • 1. Krishna  |  June 19, 2012 at 7:34 pm

    Incorrect query. First correct your query then post.

    Reply
    • 2. Pranav Rajyaguru  |  July 5, 2012 at 7:03 pm

      Krishna, Can you tell me which part of the query is wrong. You might talking about single quote, it’s not wrong query. Still, you can check now

      Reply
  • 3. moksha  |  June 23, 2012 at 5:33 pm

    thnaks………………

    Reply
  • 4. Franziska  |  May 30, 2013 at 6:22 pm

    I’ve learn some good things right here. Seriously benefit bookmarking for revisiting.

    Reply
  • 5. piano tips for beginners  |  July 8, 2013 at 4:23 pm

    Asking questions are in fact fastidious thing if you are not understanding anything entirely,
    however this article offers good understanding even.

    Reply
  • 6. fangxuela.com  |  July 11, 2013 at 1:10 am

    It’s difficult to find experienced people on this subject, but you sound like you know what you’re talking about!
    Thanks

    Reply
  • 7. central air conditioner price guide  |  July 20, 2013 at 10:18 pm

    Great goods from you, man. I have understand your stuff previous to
    and you are just too wonderful. I really like what you have acquired here, certainly like what you
    are stating and the way in which you say it. You make it
    enjoyable and you still take care of to keep it wise. I can’t wait to read much more from you. This is actually a terrific web site.

    Reply
  • 8. automatic coffee maker has special place  |  July 24, 2013 at 4:16 am

    Hey! This post couldn’t be written any better! Reading through this post reminds me of my old room mate! He always kept chatting about this. I will forward this write-up to him. Fairly certain he will have a good read. Thank you for sharing!

    Reply

Leave a reply to central air conditioner price guide Cancel reply

Trackback this post  |  Subscribe to the comments via RSS Feed


Feeds