65.9K
CodeProject is changing. Read more.
Home

SQL function to return CSV as a table

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.20/5 (2 votes)

May 12, 2010

CPOL
viewsIcon

8490

/*************...

/******************************************************************************
Function Name   : GetMyTable
Purpose         : Returns CSV as a table with each value in a row.
Execute Format  : select * from dbo.GetMyTable('1,12,14')
*******************************************************************************/

ALTER    FUNCTION [dbo].[GetMyTable]
(
    @CSV varchar(5000)
)
RETURNS @MyTable table
(
    VALUE varchar(5000)
)
as
begin
    while(charindex(',',@CSV,0) > 0)
    begin
        declare @FTEMP varchar(2000)
        set @FTEMP = substring(@CSV,0,charindex(',',@CSV))
        set @CSV = substring(@CSV,len(@FTEMP) + 2, len(@CSV))
        insert into @MyTable
        select @FTEMP
    end
    insert into @MyTable select @CSV
    return
end