Home >Database >Mysql Tutorial >How Can I Split Comma-Separated Strings in T-SQL 2008 R2?

How Can I Split Comma-Separated Strings in T-SQL 2008 R2?

DDD
DDDOriginal
2025-01-25 07:02:07695browse

How Can I Split Comma-Separated Strings in T-SQL 2008 R2?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn