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
2918 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
Parse comma separated input string in SQL
Loop through all records in Sql server with while statement
showing row details on button click of silver light datagrid
Call Codebehind method from GridView ItemTemplate Eval function
Get comma separated result of a database query
Working with silver light datagrid
Different types of alter table command to change database schema
Delete duplicate records from table in SQL
Calling web service asynchronously using jquery ajax
Working with Grid control in silverlight

Post Comment