我要求使用逗号分隔字符串(这是表列中的值) 在SQL语句的“IN”子句中(SQL server 2008) 为此,我使用下面的split函数以表格格式生成字符串,并在SQL查询的“IN”子句中使用它。
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', ',')
上面的select语句给出结果为:
Item
aaa
bbb
ccc
现在我需要使用我的SQL语句,该语句在fnSplit函数中返回字符串aaa,bbb,ccc,如下所示
select * from dbo.fnSplit((SELECT Prefix2Include FROM dbo.vw_PrefixToInclude), ',')
注意: SELECT Prefix2Include FROM dbo.vw_PrefixToInclude returns aaa,bbb,ccc
但这给了我一些语法错误,如下所示:
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near '('.
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ',
请指导我。
谢谢, Soumya
答案 0 :(得分:1)
为什么不这样试试呢
declare @Prefix2Include as Varchar(500)
SELECT @Prefix2Include = Prefix2Include FROM dbo.vw_PrefixToInclude
select * from dbo.fnSplit(@Prefix2Include , ',')
Select * From @t v
Where v.EmpPrefix IN
(select * from dbo.fnSplit(@Prefix2Include, ','))