我需要在 SQL 语句(SQL server 2008)的“IN”子句中使用逗号分隔的字符串(它是表列中的值)为此,我使用下面的拆分函数将字符串设为表格格式并在 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 ',
请指导我。
谢谢, 苏米亚