[dba-SQLServer] Fwd: Append several fields into one

David McAfee davidmcafee at gmail.com
Thu Jun 25 12:28:47 CDT 2009


This is something that I modifed from a udf that Francisco orignally wrote:

ALTER   FUNCTION [dbo].[udfListToTable] (@HList VarChar(1000), @Delimiter
CHAR(1))
RETURNS @ListTable TABLE (Mystr VARCHAR(20))
AS
BEGIN
    --Purpose: To convert a Comma delimited text to a Temp Variable table To
help avoid dynamic sql
    --         Instead you can join the temp table or use it in your where
clause if a field is IN the subquery
    DECLARE @Mystrtext as VarChar(20)

    IF RIGHT(RTRIM(@HLIST),1) <>@Delimiter
        SET @HList = @HList + @Delimiter

    WHILE CHARINDEX(@Delimiter, @HList) > 0
    BEGIN
        IF CHARINDEX(@Delimiter, @HList) > 0
           BEGIN
            SELECT @Mystrtext =LEFT(@HList, CHARINDEX(@Delimiter, @HList)-1)
           END
        ELSE
           BEGIN
             SELECT @Mystrtext = RTRIM(LTRIM(@HList))
           END
        --Insert into Variable Table
        INSERT INTO @ListTable(Mystr)
               SELECT RTRIM(LTRIM(@Mystrtext))
        --Remove Item from list
        SELECT @HList = RIGHT(RTRIM(@HList), LEN(RTRIM(@HList)) -
CHARINDEX(@Delimiter, @HList))
    END
    RETURN
END


Call it as such (from within a sproc)
SELECT * FROM dbo.udfListToTable('jim,joe,bob,tom',',')

Returns:
jim
joe
bob
tom



More information about the dba-SQLServer mailing list