Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Execute Query Every Interval

Tags:

sql

sql-server

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?

like image 607
yazanpro Avatar asked Sep 23 '13 19:09

yazanpro


People also ask

How can I run a SQL job every 1 second?

You can refer a column in a table with a bit value while checking the condition for the WHILE loop. If true the loop continues.

Can I schedule a SQL query to run automatically?

Click Start automatically when SQL Server Agent starts to start the job when the SQL Server Agent service is started. Click Start whenever the CPUs become idle to start the job when the CPUs reach an idle condition. Click Recurring if you want a schedule to run repeatedly.

How do I schedule a SQL query to run daily in SQL Server?

In the 'Steps' window enter a step name and select the database you want the query to run against. Paste in the T-SQL command you want to run into the Command window and click 'OK'. Click on the 'Schedule' menu on the left of the New Job window and enter the schedule information (e.g. daily and a time).


2 Answers

You could use WAITFOR in a loop. You would specify the interval time in the WAITFOR statement.

Something like this:

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

   SELECT * FROM MyTransactions

   -- Break on some condition
END
like image 89
Randy Minder Avatar answered Sep 30 '22 16:09

Randy Minder


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
like image 38
Bogdan Sahlean Avatar answered Sep 30 '22 16:09

Bogdan Sahlean