Sunday 17 July 2016

Converting Comma Separated Value to Rows and Vice Versa in SQL Server



Query 1: 
Using ->> COALESCE function
-----------------------------------------

DECLARE @temp VARCHAR(MAX)
SELECT @temp = COALESCE(@temp+', ' ,'') + '['+ Columnname+ ']'
FROM [dbo].[mstCombobox_Twhere Flag=33 order by SNo
SELECT @temp

// Result  

[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24]

Query 2: 
Using without ->> COALESCE function
 ------------------------------------------------
DECLARE @temp VARCHAR(MAX)
SET @temp = ''
SELECT @temp = @temp + state + ', '
FROM [dbo].[mstCombobox_Twhere Flag=33 order by SNo
SELECT SUBSTRING(@temp, 0, LEN(@temp))

// Result  

[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24]


Query 3:
Using ->> FOR XML PATH
 ---------------------------------------------------
DECLARE @temp VARCHAR(MAX)
SET @temp = (SELECT ', ' + cast(s.state as varchar)
                      FROM [dbo].[mstCombobox_T] s where Flag=33 order by SNo
                      ORDER BY s.state
                     FOR XML PATH(''))

SELECT SUBSTRING(@temp, 2, 200000) AS state


// Result 

[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19], [20], [21], [22], [23], [24]

No comments:

Post a Comment

Excel Sort values in ascending order using function TEXTJOIN

 Excel ::  Text ::  1,3,5,2,9,5,11 Result :: 1,2,3,5,5,9,11 Formula ::     TEXTJOIN ( ",",1,SORT(MID(SUBSTITUTE( A1 ,","...