这可以在不使用动态 SQL 的情况下完成,但您需要创建几个支持对象。第一个对象是一个表值函数,它将解析您的字符串并返回一个整数表。第二个对象是一个存储过程,它有一个参数,您可以在其中传递字符串 (id_list),将其解析为表,然后最后将其加入查询。
首先,创建解析字符串的函数:
CREATE FUNCTION [dbo].[String_To_Int_Table]
(
@list NVARCHAR(1024)
, @delimiter NCHAR(1) = ',' --Defaults to CSV
)
RETURNS
@tableList TABLE(
value INT
)
AS
BEGIN
DECLARE @value NVARCHAR(11)
DECLARE @position INT
SET @list = LTRIM(RTRIM(@list))+ ','
SET @position = CHARINDEX(@delimiter, @list, 1)
IF REPLACE(@list, @delimiter, '') <> ''
BEGIN
WHILE @position > 0
BEGIN
SET @value = LTRIM(RTRIM(LEFT(@list, @position - 1)));
INSERT INTO @tableList (value)
VALUES (cast(@value as int));
SET @list = RIGHT(@list, LEN(@list) - @position);
SET @position = CHARINDEX(@delimiter, @list, 1);
END
END
RETURN
END
现在创建您的存储过程:
CREATE PROCEDURE ParseListExample
@id_list as nvarchar(1024)
AS
BEGIN
SET NOCOUNT ON;
--create a temp table to hold the list of ids
CREATE TABLE #idTable (ID INT);
-- use the table valued function to parse the ids into a table.
INSERT INTO #idTable(ID)
SELECT Value FROM dbo.String_to_int_table(@id_list, ',');
-- join the temp table of ids to the table you want to query...
SELECT T1.*
FROM table1 T1
JOIN #idTable T2
on T1.ID = T2.ID
执行示例:
exec ParseListExample @id_list='1234,23,56,576,1231,567,122,87876,57553,1216'
我希望这有帮助...