Simulate Split function in T-SQL
Splitting comma-separated values into separate lines is a common task in programming. In T-SQL, there is no native split function, but there are several techniques to achieve similar results.
One way is to use XML processing. By converting the comma-delimited string into an XML document and then using XQuery to extract the values, we can populate the table with these individual values:
<code class="language-sql">DECLARE @xml xml, @str varchar(100), @delimiter varchar(10) SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15' SET @delimiter = ',' SET @xml = cast(('<X>'+replace(@str, @delimiter, '</X><X>')+'</X>') as xml) SELECT C.value('.', 'varchar(10)') as value FROM @xml.nodes('X') as X(C)</code>
An alternative is to use a recursive common table expression (CTE) to iterate over the string and extract the substrings:
<code class="language-sql">DECLARE @str varchar(100), @delimiter varchar(10) SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15' SET @delimiter = ',' ;WITH cte AS ( SELECT 0 a, 1 b UNION ALL SELECT b, CHARINDEX(@delimiter, @str, b) + LEN(@delimiter) FROM CTE WHERE b > a ) SELECT SUBSTRING(@str, a, CASE WHEN b > LEN(@delimiter) THEN b - a - LEN(@delimiter) ELSE LEN(@str) - a + 1 END) value FROM cte WHERE a > 0</code>
Many other ways to split comma separated strings in T-SQL can be found in the reference link provided in this Stack Overflow answer: How to split comma separated strings?
The above is the detailed content of How to Split Comma-Separated Strings in T-SQL?. For more information, please follow other related articles on the PHP Chinese website!