如果数据不存在等待否则运行 SQL

问题描述

建立在:Efficient way to check if a SQL query will return results

是否可以在 sql 语句的开头添加等待脚本?

IF EXISTS(
      select * from myTable 
      where id=7)

)
SELECT * From myTable
ELSE --(Wait 1 minute,then Run Again)
SELECT * From myTable

解决方法

您可以使用 WAITFOR 暂停,并使用 @@ROWCOUNT 确定查询是否返回结果。所以像:

set nocount on

drop table if exists #t;

--create an empty temp table
select * 
into #t
from tt 
where 1=0

while (1=1)
begin
  insert into #t
  select * from tt 

  if (@@ROWCOUNT > 0)
  begin
    break;
  end

   waitfor delay '00:00:05'
end

set nocount off;
select * from #t;