【问题标题】:Passing a User defined table type to SP without declaring将用户定义的表类型传递给 SP 而不声明
【发布时间】:2013-02-01 23:05:09
【问题描述】:

代码

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')

问题

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

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

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

或 声明@l IntListType 插入@l 从名称 = 'One' 的产品中选择 ProductId 执行 TestProc @l

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

exec TestProc (;with A as( select ProductId from Products where Name = 'One') select * from a)

但我无法完成这项工作。

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

【问题讨论】:

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


    【解决方案1】:

    很抱歉让您失望了,但尽管如此,目前 SQL Server 甚至不允许将简单的计算作为参数传递给过程。因此,它也不允许传入查询。

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

    【讨论】:

    • 我在两个表之间的一个小项目上进行了测试。使用“in”比使用内连接快大约 10%。这是一个小的基础,所以我不能从中得出任何结论,但我觉得,如果使用得当,它们比连接更有好处。
    • 有关IN性能的详细信息,请参阅此OP的问题stackoverflow.com/questions/1200295/sql-join-vs-in-performance
    猜你喜欢
    • 2016-07-16
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 2015-01-11
    相关资源
    最近更新 更多