Thursday, 10 December 2020

Convert comma or other delimiters to a Table or List in SQL Server

--///////// Methode 1
 
drop table #TempTbl;
DECLARE @Str NVARCHAR(MAX) = N'1, 2, 3, 4, 5, 6, 7'
DECLARE @sql_xml XML = Cast('<K>'+ Replace(@Str, ',', '</K><K>')+ '</K>' AS XML)   
SELECT f.x.value('.', 'varchar(max)')[ID] INTO #TempTbl FROM @sql_xml.nodes('/K') f(x)   
SELECT * FROM #TempTbl
 
--///////// Methode 2
 
declare @TempTbl TABLE (ID int identity(1,1),Value NVARCHAR(MAX))
DECLARE @Str NVARCHAR(MAX) = N'1, 2, 3, 4, 5, 6, 7'
DECLARE @sql_xml XML = Cast('<K>'+ Replace(@Str, ',', '</K><K>')+ '</K>' AS XML)
insert into @TempTbl(Value) 
SELECT f.x.value('.', 'varchar(max)')[value] FROM @sql_xml.nodes('/K') f(x)   
SELECT * FROM @TempTbl



//////Result


 




No comments:

Post a Comment

How to highlight selected text in notepad++

  –> To highlight a block of code in Notepad++, please do the following steps step-1  :- Select the required text. step-2  :- Right click...