SQL Split function that handles string with delimeter appearing between text qualifiers?

后端 未结 3 784
庸人自扰
庸人自扰 2021-01-25 08:09

There are several SQL split functions, from loop driven, to using xml commands, and even using a numbers table. I haven\'t found one that supports text qualifiers.

Usin

3条回答
  •  星月不相逢
    2021-01-25 08:58

    Here is my solution:

    CREATE FUNCTION fnSplitString
    (
        @input nvarchar(MAX) 
    )
    RETURNS @emails TABLE
    (
        email nvarchar(MAX) 
    )
    AS
    BEGIN
    
    DECLARE @len int = LEN(@input)
    DECLARE @pos int = 1;
    DECLARE @start int = 1;
    DECLARE @ignore bit = 0;
    WHILE(@pos<=@len)
    BEGIN
    
        DECLARE @ch nchar(1) = SUBSTRING(@input, @pos, 1);
    
        IF ( @ch = '"' or @ch = '''')
        BEGIN
            SET @ignore = 1 - @ignore;
        END
    
        IF (@ch = ',' AND @ignore = 0)
        BEGIN
            INSERT @emails VALUES (SUBSTRING(@input, @start, @pos-@start));
            SET @start = @pos+1;
        END
    
        SET @pos = @pos + 1;
    END
    
    IF (@start<>@pos)
    BEGIN
        INSERT @emails VALUES (SUBSTRING(@input, @start, @pos-@start));
    END
    
    RETURN
    END
    GO
    
    DECLARE @input nvarchar(max) = 'jsmith@anywhere.com, "Sally \"Heat\" Jones" , "Mark Jones" , "Stone, Ron" ';
    
    select * from fnSplitString(@input)
    

提交回复
热议问题