为什么我无法获取@@rowcount 值?
下面是我的 SQL 脚本的简化版本。 print @RowNum
始终显示 0,而不是第一个结果集的真实记录数。怎么了?谢谢。
declare @i int, @RowNum int
set @i=0
while @i<2
begin
execute StoredProcedure @i --containing a big select
if @i=0 set @RowNum=@@rowcount
set @i=@i+1
end
print @RowNum
Below is a simplified version of SQL script I have. print @RowNum
always shows 0, rather than the real record number of the first result set. What's wrong? Thank you.
declare @i int, @RowNum int
set @i=0
while @i<2
begin
execute StoredProcedure @i --containing a big select
if @i=0 set @RowNum=@@rowcount
set @i=@i+1
end
print @RowNum
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为这个
if @i=0
将其设置为 0,即使 print 语句也会将其设置为 0
现在运行这
是另一个示例,
现在它将是 0
PRINT 也会搞乱它,这将是 2
这将是 0
我在这里创建了一篇包含更多示例和解释的帖子: 什么时候应该将 @@ROWCOUNT 存储到变量中?
because this
if @i=0
sets it to 0, even a print statement will set it to 0
now run this
here is another example
now it will be 0
PRINT also messes it up, this will be 2
this will be 0
I created a post with more examples and explanations here: When should you store @@ROWCOUNT into a variable?
我假设 SQLMenace 的答案是正确的,但补充一下,“这不是你想要的吗?”:
I'm gonna assume SQLMenace's answer is correct, but add, "Wouldn't this do what you want?":
我一般会避免这种风格。如果在调用过程后通过查询 @@rowcount 来检索从 SP 中的表中选择的行数,则实际上引入了对过程内部实现方式的不必要依赖,并损害了明确性。如果稍后更改程序的实现,可能会破坏外部代码,并且在修改 SP 时不会很明显。您应该使用适当命名的输出参数。
I would avoid this style in general. If you retrieve the number of rows selected from a table in the SP by querying @@rowcount after the call to the procedure, you are actually introducing an unnecessary dependency on how the procedure is implemented inside and compromise explicitness. If you later change the implementation of the procedure it may break the code outside and it would not be obvious while modifying the SP. You should instead use output parameter named appropriately.