Split string in T-SQL 2008 R2
In SQL Server 2008 R2, users face challenges when trying to split comma-delimited strings. Despite searching StackOverflow, it seems that the available solutions may not be compatible with this version.
Solution
To efficiently split strings in T-SQL 2008 R2, the following user-defined functions can be used:
<code class="language-sql">CREATE FUNCTION dbo.splitstring ( @stringToSplit VARCHAR(MAX) ) RETURNS @returnList TABLE ([Name] [nvarchar] (500)) AS BEGIN DECLARE @name NVARCHAR(255) DECLARE @pos INT WHILE CHARINDEX(',', @stringToSplit) > 0 BEGIN SELECT @pos = CHARINDEX(',', @stringToSplit) SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1) INSERT INTO @returnList SELECT @name SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos) END INSERT INTO @returnList SELECT @stringToSplit RETURN END</code>
Examples of usage
To use this function, execute the following query:
<code class="language-sql">SELECT * FROM dbo.splitstring('91,12,65,78,56,789')</code>
This query will return a result table containing individual string elements separated by commas.
The above is the detailed content of How Can I Split Comma-Separated Strings in T-SQL 2008 R2?. For more information, please follow other related articles on the PHP Chinese website!