首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何等待查询返回结果?

如何等待查询返回结果?
EN

Stack Overflow用户
提问于 2012-11-08 15:09:00
回答 1查看 2.6K关注 0票数 2

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

代码语言:javascript
复制
SELECT Column1 FROM Table1

如果Table1为空,查询将返回空结果集。但是,我希望它不返回,但等待至少有一行可用,最好是某种类型的超时。如果可能的话,我更愿意这样做,而不让Service参与其中。

Clarification:

CLR是在服务器上启用的,但是调用是通过SQLAPI++/ODBC从一个独立于平台的C++程序进行的。因此,C#/.NET技巧是不可能的。目标是对存储过程进行调用,指定超时,直到数据可用(并由存储的proc返回)或指定的超时过期为止才返回。

例如:

代码语言:javascript
复制
EXEC GetData @Timeout=2000 -- Wait for upto 5000 milliseconds for a result set to be 
                           -- available
EN

回答 1

Stack Overflow用户

发布于 2012-11-08 16:41:01

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

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13291710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档