Click here to check my latest exciting videos on youtube
Search Mallstuffs

Flag Counter
Spirituality, Knowledge and Entertainment


Locations of visitors to this page


Latest Articles


Move to top
Get comma separated result of a database query
Posted By Sarin on Nov 30, 2012     RSS Feeds     Latest Hinduism news
2770 Views

Sometimes you may have the requirement to display the result of the database query as a comma separated values. For example in a blogging website, you may want to show the list of comma separated users who liked a particular article.
 
As an example, below query gets the list of all users from userinfo table
  
SELECT SUBSTRING(
(
SELECT ',' + username
FROM UserInfo FOR XML PATH('')),2,200000) AS users
  
Below is the output of this query. I have three users in my sample database and as you can see below, all his three users are shown in a single column as comma separated values.


  
You can also add a Filter condition as
SELECT SUBSTRING(
(
SELECT ',' + username
FROM UserInfo  where location='US' FOR XML PATH('')),2,200000) AS users
  
Alternatively, you can use the below query to do the same  
DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' ,'') + username  
FROM UserInfo
SELECT @listStr as 'users'

Hope this tip was useful to you


Note: Images used on this website are either a production of Bhaktivedanta Book Trust(https://www.krishna.com), Iskcon Foundation or were found in google search under "Free to use and share". If any of the images presented here violates copyright issues or infringes anyone copyright or are not under "Fair use", then please bring it to our notice. Read Disclaimer for more.

Share this to your friends. One of your friend is waiting for your share.
Share on Google+ Share on Tumblr Print Browser Favorite
Related Articles
Get comma separated result of a database query
Calling web service asynchronously using jquery ajax
Call Codebehind method from GridView ItemTemplate Eval function
Changing Grid View header and footer at run time
When to use optional parameters of creating database statement
Working with Grid control in silverlight
Loop through all records in Sql server with while statement
showing row details on button click of silver light datagrid
Delete duplicate records from table in SQL
Get All Tables in a Database

Post Comment