How to validate a comma separated string using array in SQL

前端 未结 1 982
Happy的楠姐
Happy的楠姐 2021-01-16 07:51

I have to create a function in sql which will validate a comma separated string.

example: string will be like @str = \'AB,CD,EF,GH\'

I have

1条回答
  •  悲哀的现实
    2021-01-16 08:54

    This function will take your comma separated list and return a table, just like STRING_SPLIT() which I think is only available for SQL Server 2016. Then, you'll just INNER JOIN to the table based on your conditions. I usually set a table variable to the results of this function so I can reuse it.

    ALTER FUNCTION [dbo].[ufn_split_string]
    (    
        @RowData NVARCHAR(MAX),
        @Delimeter NVARCHAR(MAX)
    )
    RETURNS @RtnValue TABLE 
    (
        ID INT IDENTITY(1,1),
        DataRow NVARCHAR(MAX)
    ) 
    AS
    BEGIN 
        DECLARE @Iterator INT
        SET @Iterator = 1
    
        DECLARE @FoundIndex INT
        SET @FoundIndex = CHARINDEX(@Delimeter,@RowData)
    
        WHILE (@FoundIndex>0)
        BEGIN
            INSERT INTO @RtnValue (DataRow)
            SELECT 
                Data = LTRIM(RTRIM(SUBSTRING(@RowData, 1, @FoundIndex - 1)))
    
            SET @RowData = SUBSTRING(@RowData, 
                    @FoundIndex  + 1,
                    LEN(@RowData))
    
            SET @Iterator = @Iterator + 1
            SET @FoundIndex = CHARINDEX(@Delimeter, @RowData)
        END
    
        INSERT INTO @RtnValue (DataRow)
        SELECT Data = LTRIM(RTRIM(@RowData))
    
        RETURN
    END
    
    GO
    

    0 讨论(0)
提交回复
热议问题