How to split string and insert values into table in SQL Server

前端 未结 8 637
青春惊慌失措
青春惊慌失措 2020-11-29 12:36

I have a string like this:

72594206916,2,1/2/08,Tacoma,WA:72594221856,5,5/7/13,San Francisco,CA:72594221871,99,12/30/12,Dallas,TX

This is b

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 12:36

    Create this SQL function:

    CREATE FUNCTION [dbo].[StringSplit](@input NVARCHAR(MAX), @delimiter CHAR(1)=',') 
           RETURNS @returnTable TABLE(item NVARCHAR(100)) AS  
         BEGIN 
            IF @input IS NULL RETURN;
            DECLARE @currentStartIndex INT, @currentEndIndex INT,@length INT;
            SET @length=LEN(@input);
            SET @currentStartIndex=1;
    
            SET @currentEndIndex=CHARINDEX(@delimiter,@input,@currentStartIndex);
            WHILE (@currentEndIndex<>0)
              BEGIN
                INSERT INTO @returnTable VALUES (LTRIM(SUBSTRING(@input, @currentStartIndex, @currentEndIndex-@currentStartIndex)))
                SET @currentStartIndex=@currentEndIndex+1;
                SET @currentEndIndex=CHARINDEX(@delimiter,@input,@currentStartIndex);
              END
    
            IF (@currentStartIndex <= @length)
              INSERT INTO @returnTable 
                VALUES (LTRIM(SUBSTRING(@input, @currentStartIndex, @length-@currentStartIndex+1)));
            RETURN;
         END;
    

    Usage example:

    DECLARE @testString VARCHAR(100)
    SET @testString = '72594206916,2,1/2/08,Tacoma,WA:72594221856,5,5/7/13,San Francisco,CA:72594221871,99,12/30/12,Dallas,TX'
    
    SELECT *
    FROM [dbo].[StringSplit](@testString, DEFAULT)
    

    Result (table):

    72594206916
    2
    1/2/08
    Tacoma
    WA:72594221856
    5
    5/7/13
    San Francisco
    CA:72594221871
    99
    12/30/12
    Dallas
    

提交回复
热议问题