Search code examples
sqlasp-classicdelaydelayed-execution

How can I make a SQL script run after a certain time without waiting for it?


I'm trying to create a SQL script with a delay.

I could use:

blah blah
WAITFOR DELAY '00:30:00'
blah blah

but using a script like this requires that I sit through the 30 minutes.

Leaving the website will cancel the script.


The problem is that I want to change something in a table, and then change it back automatically 30 minutes later.

The person making the change will leave the webpage, so any kind of client-side script is out of the question.

Nor can I wait for the person to return and make the change if 30 minutes have passed, the change must happen after 30 minutes regardless.


Is there anyway to do this without making a service or any other program on the server?

Using only ASP/SQL programming.

If this is impossible, how do I make a service or program on the server to make this change?

Must be able to start this from the website using ASP.


Solution

  • Figured it out by using SQL Server Agent and SQL procedures.

    This is basically how my code is built up now:

    Make the temporary change in the table

    UPDATE table SET column = 'temp_value' WHERE column = 'normal_value'
    

    Check if the procedure is there, if so, delete it. Create a procedure to revert the changes in the table.

    IF EXISTS ( SELECT * 
        FROM sys.objects 
        WHERE object_id = OBJECT_ID(N'myRevertProcedure')
            AND type IN ( N'P', N'PC' ) )
        DROP PROCEDURE myRevertProcedure 
    
    CREATE PROCEDURE myRevertProcedure 
        AS
        BEGIN 
            WAITFOR DELAY '00:30:00'
            UPDATE table SET column = 'normal_value' WHERE column = 'temp_value'
        END
    

    I've created a job in the SQL Server Agent that runs the following:

    IF EXISTS ( SELECT * 
        FROM sys.objects 
        WHERE object_id = OBJECT_ID(N'myRevertProcedure')
            AND type IN ( N'P', N'PC' ) )
        BEGIN
            EXEC MyProc
            DROP PROCEDURE myRevertProcedure 
        END
    

    The reason the job does not simply revert the change itself is because the user shall set the delay.

    If the delay were allways to be 30 mins, I could've made the job run the following:

    IF EXISTS (SELECT * FROM table WHERE column = 'temp_value')
        BEGIN
            WAITFOR DELAY '00:30:00'
            UPDATE table SET column = 'normal_value' WHERE column = 'temp_value'
        END
    

    By doing this, I would not need any procedure.

    BTW: The job runs every few seconds.