Guruji Point - Code You Want To Write

  • Home
  • Asp.Net
  • WCF
  • SQL
  • Type Script
  • AngularJS
  • Tech News
  • Blog
  • Earn Online

Saturday, 17 June 2017

Transform Multiple Rows Into One Comma Separated Value In SQL Server

 SQL     No comments   


Introduction
In this article we will learn How to convert multiple rows into one  comma separated value? Convert many rows into a single text string with any separator. 

Previous Updates

In previous articles we have learnt Best basic C# interview questions. what is TypeScript and How to Install this on VS2015 .AngularJS basics, What is Cursor in sql and use of cursor. 


Description
Many of use comes across this problem while working with tables and data. Here i explain this in three different methods using them you can easily convert or transform your multiple row data into single row data.


CREATE TABLE MytemData( ID INT IDENTITY(1,1), Code VARCHAR(50))

Insert into MyTempData values ('AC')
Insert into MyTempData values ('95')
Insert into MyTempData values ('79')
Insert into MyTempData values ('BL')
Insert into MyTempData values ('CDC')
Insert into MyTempData values ('IIA')
Insert into MyTempData values ('MNC')

1st Method :-

DECLARE @temp VARCHAR(MAX)
SET @temp = (SELECT ', ' + cast(Code as varchar)
                      FROM [dbo].[MyTempData]
                      ORDER BY Code
                     FOR XML PATH(''))
SELECT SUBSTRING(@temp, 2, 200000) AS Code


2nd Method :-
DECLARE @temp VARCHAR(MAX)
SET @temp = ''
SELECT @temp = @temp + Code + ', '
FROM [dbo].[MyTempData]
SELECT SUBSTRING(@temp, 0, LEN(@temp))
3rd Method :-

DECLARE @temp VARCHAR(MAX)
SELECT @temp = COALESCE(@temp+', ' ,'') + Code
FROM [dbo].[MyTempData]
SELECT @temp

And after performing all of these three methods always your output looks like this.


  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home
View mobile version

0 comments:

Post a Comment

Facebook Updates

Guruji Point

Categories

Comman table Expression in SQL Dynamic Grid Row IQueryable in c# Learn AngularJS Scope_Identity() Use of indexes comma seperated string in sql row_number() and dense_rank() salary table structure. while loop in sql why do we need cursor why tuple used

About Us

This blog is about the Programming ,Tech News and some intresting facts related Contents. Here you can find fundamental and expert level topic of programming languages very practically related to C# , Asp.Net ,Sql-Server, JavaScript, Jquery, WebServices And also Web-Api, WCF ,WPF, Angular Js.

Contact Us

Email Us - gurujipoints@gmail.com
Contact- 8077657477

Reach Us

Copyright © Guruji Point - Code You Want To Write