Translate

Function to get comma separated string as table in SQL Server


Following function will return comma separated string as a table:

CREATE FUNCTION [dbo].[util_fnc_comma_delim_to_table] (@vc_item_list varchar(MAX))
RETURNS
@tbl_parsed_list table (vc_text varchar(MAX))
AS
BEGIN
    DECLARE @vc_text varchar(100), @in_position int
   
    SET @vc_item_list = LTRIM(RTRIM(@vc_item_list))+ ','
    SET @in_position = CHARINDEX(',', @vc_item_list, 1)
   
    IF REPLACE(@vc_item_list, ',', '') <> ''
    BEGIN
        WHILE @in_position > 0
        BEGIN
            SET @vc_text = LTRIM(RTRIM(LEFT(@vc_item_list, @in_position - 1)))
            IF @vc_text <> ''
            BEGIN
                INSERT INTO @tbl_parsed_list (vc_text)
                VALUES (CAST(@vc_text AS varchar)) --Use Appropriate conversion
            END
            SET @vc_item_list = RIGHT(@vc_item_List, LEN(@vc_item_list) - @in_position)
            SET @in_position = CHARINDEX(',', @vc_item_list, 1)
        END
    END   
    RETURN
END

Use Following statement to check result:

SELECT * FROM dbo.util_fnc_comma_delim_to_table('1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15')

Example to get records from a table by using this function:

SELECT * FROM dbo.employee WHERE in_employee_id IN (SELECT * FROM dbo.util_fnc_comma_delim_to_table('1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15'))



No comments:

Post a Comment