2

我正在使用 SQL Server 并且在存储过程中我想使用如下列表参数执行查询:

select * from table where type in @list_types

有可能做到这一点吗?或者我必须使用临时表吗?

4

2 回答 2

2

您可以使用表值参数。例如:

-- 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 支持将 aDataTable作为表值参数传递。

于 2013-05-22T08:01:24.143 回答
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)
于 2013-05-22T07:57:39.393 回答