最有效的方法是使用动态 SQL,例如 rt2800 提及(Michael Allen 的注入警告)
但是,您可以创建一个函数:
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 时,这非常有用。