1

我需要在 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 ',

请指导我。

谢谢, 苏米亚

4

2 回答 2

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, ','))
于 2012-11-05T05:17:51.490 回答
1

CROSS JOIN 指定两个表的叉积。返回与在旧式非 SQL-92 式联接中未指定 WHERE 子句时相同的行。

SELECT item FROM dbo.vw_PrefixToInclude CROSS APPLY dbo.fnSplit(Prefix2Include, ',')

用于 sql 2016 或更高版本

SELECT value FROM dbo.vw_PrefixToInclude CROSS APPLY STRING_SPLIT(Prefix2Include, ',')

要更改数据库的兼容级别,请参阅查看或更改数据库的兼容级别。 https://docs.microsoft.com/en-us/sql/relational-databases/databases/view-or-change-the-compatibility-level-of-a-database?view=sql-server-ver15

于 2021-12-16T21:07:10.897 回答