2

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

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
4

1 回答 1

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
于 2012-11-08T16:41:01.137 回答