Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

SQL Server - Query to Concatenate Row Values in SQL Server

Jul 21, 2012
Introduction:

In this article I will explain how to write a query to concatenate row values in SQL server.

Description:

In previous post I explained how to concatenate column values in SQL Server and many articles relating to SQL Server. Now I will explain how to write a query to concatenate row values in SQL Server. Here I will explain with one example for that I have one table UserDetails like as shown below

Now I want bind the username row values into single row like as shown below

If we want to concatenate one column row values into single row we need to write query like this


DECLARE @name NVARCHAR(MAX)
SELECT @name = COALESCE(@name + ',', '') + UserName FROM UserDetails
SELECT UserNames = @name
If you observe above query I used function COALESCE it returns the first non-null expression among its arguments.

OutPut

We can concatenate rows in another way also

Another way

If we want to concatenate rows of column we can write query like as shown below

DECLARE @name NVARCHAR(MAX)
SET @name=''
SELECT @name = @name +','+UserName  FROM UserDetails
SET @name = Substring(@name, 2, (len(@name)))
SELECT @name as UserNames
OutPut


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

2 comments :

Santhosha said...

Dear Sir, Could you please explain the second method step by step please i am not getting, first method also showing error

Anonymous said...

Please update dynamic query to bind the data for reports table from dropdown based selected values

Give your Valuable Comments

Other Related Posts

© 2010-2012 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.