I have a requirement to use a comma seperated string (which is a value in a table column) in 'IN' clause of an SQL statement(SQL server 2008) For this I am using below split function to make the string in a tabular format and use it in the 'IN' clause of an SQL query.
ALTER FUNCTION dbo.fnSplit(
@sInputList VARCHAR(8000) -- List of delimited items
, @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS @List TABLE (item VARCHAR(8000))
BEGIN
DECLARE @sItem VARCHAR(8000)
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
BEGIN
SELECT
@sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX
(@sDelimiter,@sInputList,0)-1))), @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX
(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
IF LEN(@sItem) > 0
INSERT INTO @List SELECT @sItem
END
IF LEN(@sInputList) > 0
INSERT INTO @List SELECT @sInputList -- Put the last item in
RETURN
END
GO
select * from dbo.fnSplit('aaa,bbb,ccc', ',')
Above select statement gives result as:
Item
aaa
bbb
ccc
Now I need to use my SQL statement which returns the string aaa,bbb,ccc in the fnSplit function as below
select * from dbo.fnSplit((SELECT Prefix2Include FROM dbo.vw_PrefixToInclude), ',')
Note: SELECT Prefix2Include FROM dbo.vw_PrefixToInclude returns aaa,bbb,ccc
But this gives me some syntax error as below:
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near '('.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ',
Please guide me on this.
Thanks, Soumya