How to Split a string by delimited char in SQL Server

It is from
http://www.sqlservercentral.com/blogs/querying-microsoft-sql-server
/2013/09/19/how-to-split-a-string-by-delimited-char-in-sql-server/
A Stored Procedures for testing this function. 

-- =============================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF EXISTS (SELECT * FROM SYS.objects WHERE name = 'testfnSplitString' AND [TYPE] = 'P')
DROP PROCEDURE dbo.testfnSplitString 
GO
CREATE PROCEDURE dbo.testfnSplitString
(@IDs NVARCHAR(MAX))
AS
SET NoCount ON          
SET Ansi_Warnings OFF 
 DECLARE @output TABLE(IDt NVARCHAR(MAX))
 DECLARE @start INT, @end INT,@delimiter VARCHAR(2)=','
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @IDs) 
    WHILE @start < LEN(@IDs) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@IDs) + 1
       
        INSERT INTO @output (IDt)  
        VALUES(SUBSTRING(@IDs, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @IDs, @start)
    END 
select * from @output
-- ============================================= 

CREATE FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1
       
        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)
        
    END 
    RETURN 
END 
select *from dbo.fnSplitString('Querying SQL Server','') 

评论

此博客中的热门博文

XML, XSL, HTML

Input in element.eleme.io

Data URI是由RFC 2397 ACE