Friday, October 11, 2019

SQL Server Query to convert the List of strings into comma delimited string

The following code was fun to convert the list of strings into comma delimited string.
create table x(destinationTableName varchar(8000))
insert into table x('a')
insert into table x('b')
insert into table x('c')
insert into table x('d')
insert into table x('e')
insert into table x('f')

WITH expression_name (sequence,destinationTableName)
AS
(
    -- Anchor member
select cast(no as int) no,cast(destinationtableName as varchar(8000))+',' as destinationtableName from
    (select row_number() over( order by red_code) as no,destinationtableName from red_searchdomain where
  insertRecords =1) x
  where no =1
    UNION ALL
    -- Recursive member that references expression_name.
    select cast(y.no as int) no,cast(expression_name.destinationtableName+y.destinationtableName+',' as varchar(8000)) destinationtableName from expression_name
join (select row_number() over( order by red_code) as no,destinationtableName from red_searchdomain where
  insertRecords =1) y
  on y.no = expression_name.sequence+1

)
-- references expression name
SELECT substring(destinationTableName,1,len(destinationTableName)-1)
FROM   expression_name where sequence =(select max(sequence) from expression_name)

No comments:

Post a Comment