6

I would like to execute a query in the Management Studio every 3 seconds for monitoring/maintenance needs. I know I can define a job or use an external application. But I 'm looking for something much simpler. Something like the following pseudo:

DECLARE @Interval INT
SET @Interval = 3000 -- I'm expecting milliseconds
BEGINLOOP (@Interval)
    SELECT * FROM MyTransactions
ENDLOOP

I would like the output to refresh every 3 seconds. Is that possible?

4

4 回答 4

10

您可以在循环中使用 WAITFOR。您将在 WAITFOR 语句中指定间隔时间。

像这样的东西:

WHILE 1=1
BEGIN
   WAITFOR DELAY '00:00:05' -- Wait 5 seconds

   SELECT * FROM MyTransactions

   -- Break on some condition
END
于 2013-09-23T19:38:59.770 回答
0
DECLARE @Interval INT;
SET @Interval = 3000;

DECLARE @Delay DATETIME;
SET @Delay = DATEADD(MILLISECOND, @Interval, 0);

DECLARE @i INT;
SET @i = 1;
WHILE @i <= 1000
BEGIN
    WAITFOR DELAY @Delay;

    PRINT @i; -- Do something

    SET @i = @i + 1;
END
于 2013-09-23T19:39:11.613 回答
0
DECLARE @i INT = 1;

WHILE (@i <= 60)
 BEGIN
  WAITFOR DELAY '00:00:05'

       /*Your Script*/

 SET  @i = @i + 1;
END 
print 'completed'
于 2017-01-29T05:21:31.377 回答
0

我只是想分享另一种可能性。避免等待整个查询结束。

DECLARE @initialTime AS datetime = getdate()
    , @duration AS INT = 15 --in seconds
    , @interval AS INT = 3 --in seconds
    , @amountOfCycles AS INT = 0

DECLARE @maxTime as datetime = dateadd(second,@duration,@initialTime)

WHILE @initialTime <= @maxTime
BEGIN
    --WAITFOR DELAY '00:00:01'
    SET @amountOfCycles += 1

    IF DATEDIFF(second,@initialTime,GETDATE()) >= @interval 
    BEGIN 
        print 'do something'
        SET @initialTime = GETDATE()
    END
    
END

PRINT '@amountOfCycles: ' + ISNULL(CONVERT(VARCHAR,@amountOfCycles),'')

我省略了WAITFOR DELAY命令(内部WHILE)。但是,我注意到我的示例中的循环次数为 15 秒,这个循环花费了将近 200 万次……内存太多了。

@amountOfCycles: 1798079

应该考虑到,但这是另一种可能。

但是,就目前而言,它解决了@yazanpro 的疑问

于 2022-01-31T23:41:14.967 回答