我正在使用SQL Server,在存储过程中,我想使用list参数执行查询,如下所示:
select * from table where type in @list_types
有可能做到这一点吗?或者我必须使用临时表吗?
答案 0 :(得分:2)
您可以使用table-valued parameters。例如:
-- A table valued parameter must have a type.
-- This command creates the type.
create type YourType as table (type varchar(50))
go
create procedure dbo.YourStoredProcedure(
@types YourType readonly)
as
select *
from YourTable
where type in (select type from @types)
go
您可以像这样调用存储过程:
declare @types YourType
insert @types (type) values ('Type1'), ('Type2')
exec dbo.YourStoredProcedure @types
ADO.NET支持将DataTable
作为表值参数传递。
答案 1 :(得分:1)
试试这个 -
DECLARE @temp TABLE
(
[type] INT
, name NVARCHAR(50)
)
INSERT INTO @temp ([type], name)
VALUES
(1, '1'),
(2, '2')
DECLARE @list_types VARCHAR(30)
SELECT @list_types = '1,3,4,5'
;WITH cte AS
(
SELECT [type] = p.value('(./s)[1]', 'INT')
FROM (
SELECT field = CAST('<r><s>' + REPLACE(@list_types, ',', '</s></r><r><s>') + '</s></r>' AS XML)
) d
CROSS APPLY field.nodes('/r') t(p)
)
SELECT *
FROM @temp
WHERE [type] IN (SELECT [type] FROM cte)