Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STRING_SPLIT in SQL Server 2012

Tags:

I have this parameter

@ID varchar = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20'  

I want to do something to split the comma-separated values.

The string_split function doesn't work and I get this error:

The STRING_SPLIT function is available only under compatibility level 130

and I try to alter my database and set the compatibility to 130 but I don't have a permission for this change.

like image 506
Moh Avatar asked Oct 24 '17 05:10

Moh


People also ask

How do I split a string with spaces in SQL Server 2012?

You can split the string using XML . You first need to convert the string to XML and replace the space with start and end XML tags . Once the string is converted into XML , you can use XQuery to get the result in proper format.

How do I split a string in SQL Server 2014?

The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and ' ' as the second argument.


1 Answers

Other approach is too use XML Method with CROSS APPLY to split your Comma Separated Data :

SELECT Split.a.value('.', 'NVARCHAR(MAX)') DATA FROM (     SELECT CAST('<X>'+REPLACE(@ID, ',', '</X><X>')+'</X>' AS XML) AS String ) AS A CROSS APPLY String.nodes('/X') AS Split(a); 

Result :

DATA 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 

Example :

DECLARE @ID NVARCHAR(300)= '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20'; DECLARE @Marks NVARCHAR(300)= '0,1,2,5,8,9,4,6,7,3,5,2,7,1,9,4,0,2,5,0'; DECLARE @StudentsMark TABLE (id    NVARCHAR(300),  marks NVARCHAR(300) );  --insert into @StudentsMark  ;WITH CTE      AS (      SELECT Split.a.value('.', 'NVARCHAR(MAX)') id,             ROW_NUMBER() OVER(ORDER BY                              (                                  SELECT NULL                              )) RN      FROM      (          SELECT CAST('<X>'+REPLACE(@ID, ',', '</X><X>')+'</X>' AS XML) AS String      ) AS A      CROSS APPLY String.nodes('/X') AS Split(a)),      CTE1      AS (      SELECT Split.a.value('.', 'NVARCHAR(MAX)') marks,             ROW_NUMBER() OVER(ORDER BY                              (                                  SELECT NULL                              )) RN      FROM      (          SELECT CAST('<X>'+REPLACE(@Marks, ',', '</X><X>')+'</X>' AS XML) AS String      ) AS A      CROSS APPLY String.nodes('/X') AS Split(a))      INSERT INTO @StudentsMark             SELECT C.id,                    C1.marks             FROM CTE C                  LEFT JOIN CTE1 C1 ON C1.RN = C.RN; SELECT * FROM @StudentsMark; 
like image 147
Yogesh Sharma Avatar answered Nov 09 '22 03:11

Yogesh Sharma