我有以下代码,问题是我的变量列表@LocationList本质上是一个csv字符串.当我使用它作为(@LocationList)中LocationID的一部分时,它表示它不是一个int(LocationID是一个int).如何让这个csv字符串被teh in子句接受?
Declare @LocationList varchar(1000) Set @LocationList = '1,32' select Locations from table where Where LocationID in (@LocationList)
解决方法
最有效的方法是使用动态sql,例如rt2800提及(由迈克尔艾伦注射警告)
但是你可以做一个功能:
ALTER FUNCTION [dbo].[CSVStringsToTable_fn] ( @array VARCHAR(8000) ) RETURNS @Table TABLE ( value VARCHAR(100) ) AS BEGIN DECLARE @separator_position INTEGER,@array_value VARCHAR(8000) SET @array = @array + ',' WHILE PATINDEX('%,%',@array) <> 0 BEGIN SELECT @separator_position = PATINDEX('%,@array) SELECT @array_value = LEFT(@array,@separator_position - 1) INSERT @Table VALUES ( @array_value ) SELECT @array = STUFF(@array,1,@separator_position,'') END RETURN END
并从中选择:
DECLARE @LocationList VARCHAR(1000) SET @LocationList = '1,32' SELECT Locations FROM table WHERE LocationID IN ( SELECT * FROM dbo.CSVStringsToTable_fn(@LocationList) )
要么
SELECT Locations FROM table loc INNER JOIN dbo.CSVStringsToTable_fn(@LocationList) list ON list.value = loc.LocationID
当您尝试从SSRS向PROC发送多值列表时,这非常有用.