将用户定义的表类型传递给SP而不声明

时间:2013-02-01 14:51:44

标签: sql-server-2008 user-defined-types

代码

create TYPE [dbo].[IntListType] as Table
(
[Number] [int] null
)

create procedure TestProc
(
    @l IntListType readonly
)
as
begin
    select * from products where ProductId in (select Number from @l)
end

create Table Products
(
    ProductId
    ProductName
)

insert into Products Values(1, 'One'),
                           (2, 'One'),
                           (3, 'Two'),
                           (4, 'Two'),
                           (5, 'Three'),
                           (6, 'Three')

问题

注意:这只是一个示例,将查询放在存储过程中似乎很容易,但这只是为了了解我想要做什么。实时它并不像在这个例子中那么容易。

目前我希望按产品收集几种产品我必须这样做:

declare @l IntListType
insert into @l values(1),(2) 
exec TestProc @l

或     声明@l IntListType     插入@l     从产品中选择ProductId,其中Name ='One'     exec TestProc @l

我想知道是否可以跳过声明部分并将选择结果创建为IntListType。 我试图用“With”

来做到这一点
exec TestProc (;with A as( select ProductId from Products where Name = 'One') select * from a)

但我无法做到这一点。

甚至可能我正在尝试做什么,或者,如果我使用用户定义的表类型,我是否总是需要在它工作之前声明并填充它?

1 个答案:

答案 0 :(得分:1)

很抱歉让您失望,但是它确实很好,目前SQL Server甚至不允许将简单计算作为参数传递给过程。因此,它不允许在任何一个中传递查询。

另外,IN不应与子查询一起使用,因为这有时会导致性能问题。请改为使用EXISTS或直接JOIN