如何等待查询返回结果?

时间:2012-11-08 15:09:00

标签: sql-server-2008 tsql sql-server-2008-r2

是否可以让查询等到结果有效,而不是立即返回空结果集。例如:

SELECT Column1 FROM Table1

如果Table1为空,则查询将返回空结果集。但是,我希望它不返回,但要等到至少有一行可用,最好是某种超时。如果可能的话,我更愿意在不涉及Service Broker的情况下这样做。

澄清:

在服务器上启用了CLR,但调用来自独立于平台的C ++程序,通过SQLAPI ++ / ODBC。所以,没有C#/ .NET技巧是可能的。目标是调用存储过程,指定超时,直到数据可用(并由存储过程返回)或指定的超时到期时才返回。

例如:

EXEC GetData @Timeout=2000 -- Wait for upto 5000 milliseconds for a result set to be 
                           -- available

1 个答案:

答案 0 :(得分:0)

丑陋但有效。只要正在执行的查询是低成本的,例如,等待行显示在空表中,这不应该是资源中的太多。

declare @Timeout as Int = 5000 -- Milliseconds.

-- Start and end times.
declare @Now as DateTime = GetDate()
declare @TimeoutExpiration as DateTime = DateAdd( ms, @Timeout, @Now )

-- Set the delay interval to the smaller of  @Timeout / 10   or   1 second.
declare @DelayInterval as Time = DateAdd( ms, @Timeout / 10, 0 )
if @DelayInterval > '00:00:01.000'
  set @DelayInterval = '00:00:01.000'
declare @WaitForDelay as VarChar(12) = Cast( @DelayInterval as VarChar(12) )  -- WaitFor insists on a truncated string for the delay.

select @Timeout as 'Timeout (ms)', @Now as 'Now', @TimeoutExpiration as 'TimeoutExpiration', @DelayInterval as 'DelayInterval'

declare @Result as Table ( Foo Int ) -- Modify to match the schema of your expected results.

-- Execute the query in a loop until either a result is returned or the timeout expires.
declare @RowCount as Int = 0
declare @Iterations as Int = 0
while @TimeoutExpiration >= GetDate() and @RowCount = 0
  begin
  -- Randomly decide to insert a row into the results.  (Replace with your query.)
  insert into @Result
    select 42 as Foo
      where Rand() > 0.8
  -- Handle the query result.
  set @RowCount = @@RowCount
  if @RowCount = 0
    waitfor delay @WaitForDelay
  set @Iterations = @Iterations + 1
  end

-- Return the result.
select @Iterations as 'Iterations' -- Just for demonstration purposes.
select *
  from @Result
相关问题