SQL Server中如何检查表变量是否为空?
这是我的一个存储过程的一部分:
@dataInTable dbo.Table_Variable readonly,
....
AND (
( @dataInTable IS NULL )
OR
( item IN ( SELECT T FROM @dataInTable ) )
)
@dataInTable IS NULL
语法错误,错误是
必须声明标量变量“@dataInTable”
,所以我将其更改为:
(SELECT T FROM @dataInTable) IS NULL
这有效,但如果 @dataInTable
有超过 1 个项目,我会收到错误:
子查询返回超过 1 个值。这是不允许的,当 子查询跟在 =、!=、<、<=、>、>= 之后,或者当子查询用作 一个表达式。
可以理解,所以我将其更改为:
(SELECT TOP(1) T FROM @ProgramRatings) IS NULL
完美运行,我所关注的是性能问题。
我想知道是否有更简单的方法来检查表变量是否为空,例如
AND (
( @dataInTable IS EMPTY )
OR
( item IN ( SELECT T FROM @dataInTable ) )
)
This is a section of one of my stored procedure:
@dataInTable dbo.Table_Variable readonly,
....
AND (
( @dataInTable IS NULL )
OR
( item IN ( SELECT T FROM @dataInTable ) )
)
@dataInTable IS NULL
is wrong in syntax, error is
Must declare the scalar variable "@dataInTable"
So I change it to:
(SELECT T FROM @dataInTable) IS NULL
This works but if @dataInTable
has more than 1 item, I get an error:
Subquery returned more than 1 value. This is not permitted when the
subquery follows =, !=, <, <= , >, >= or when the subquery is used as
an expression.
Understandable, so I change it to:
(SELECT TOP(1) T FROM @ProgramRatings) IS NULL
Works perfectly, what I have is performance concern.
I am wondering, if there has an easier way to check whether a table variable is empty, like
AND (
( @dataInTable IS EMPTY )
OR
( item IN ( SELECT T FROM @dataInTable ) )
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
表变量与标量变量不同,因此正如您提到的那样,不允许使用
@dataInTable IS NULL
。我建议如下:如果您确实想知道计数,那么以下内容也可能适合您的情况:
Table variables are different from scalar variables so
@dataInTable IS NULL
is not allowed as you mentioned. I would suggest the following:The following also may make sense for your situation if you actually care to know the count:
总有
存在
。例如:
There's always
exists
.For example:
要检查表变量是否为空,只需使用其他人已经提到的 EXISTS,
但是
如果您将空集与未知集不同 - 那么您别无选择 - 您必须引入额外的变量,该变量声明如果空集确实是空的或未知的。
For check if table variable is empty, just use EXISTS as already mentioned by other people,
but
if you differ empty set from unknown set - then you have no choice - you have to introduce extra variable which states if empty set is really empty or unknown.