Search code examples
sqlsql-server-2017

If Data Does Not Exist Wait Else RUN SQL


Building off of: Efficient way to check if a SQL query will return results

Is it possible to have a wait script added at the beginning of a SQL statement ?

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

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

Solution

  • You can use WAITFOR to pause, and @@ROWCOUNT to determine whether a query returned results. So something like:

    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;