sql-server - 为什么是无限循环?

标签 sql-server sql-server-2008 tsql

以下代码将无限循环。然而,在SSMS中停止查询后,表为空。将 if @id is not null 更改为 if @@rowcount > 0 将获得预期结果。为什么当#t为空时@id没有得到空值?

select 100 id into #t
l:
declare @id int
select top 1 @id = Id from #t 

if @id is not null
begin
    print @id

    --begin try
        raiserror ('Test error', 16, 10)
    --end try
    --begin catch
    --end catch  
    delete from #t where Id = @id
    goto l
end
(1 row(s) affected)
100
Msg 50000, Level 16, State 10, Line 10
Test error

(1 row(s) affected) --------- The row was deleted here.
100
Msg 50000, Level 16, State 10, Line 10
Test error

(0 row(s) affected)
100
Msg 50000, Level 16, State 10, Line 10
Test error

......

更新:
select top 1 @id = Id from #t 更改为 set @id = (select top 1 Id from #t) 效果很好。

最佳答案

如果#t为空,此选择不会为@id分配值:

select top 1 @id = Id from #t 

修复它的一种方法:

set @id = null
select top 1 @id = Id from #t 

关于sql-server - 为什么是无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17440475/

相关文章:

sql - T-SQL 选择两个整数列的总和

sql-server - 在 ORDER BY 子句中无效,因为它不包含在聚合函数或 GROUP BY 子句中

sql - 如何将存储过程的多个输出抓取到临时表中

sql - 如何从整数值中拆分十进制值?

sql - 如果记录作为外部表存在于另一个表中,如何不删除?

sql - XACT_ABORT 不回滚 SQL Server 2012 上的事务

sql-server - 使用远程SQL Server数据库安装Team Foundation Server

sql-server - 如何使用 TSQL 识别记录中的记录模式序列?

sql - 如何在 SQL Server 上的触发器中编辑 INSERT 的值?

sql - 表的主键是否有索引?