Can I set timeout for a query?

  • Is there a way to "timeout" a query? Assume I'm coding a long sql-query. A part of the query, I don't want to run it if takes more than X seconds, then I want to abort (throw exception or something). Is it possible?

    Google hasn't helped me so far..

     

  • any of the SQL Clients allows you to setup a command execution timeout - that is for the full execution of either a single query or the whole of a Stored proc.

    The above is the normal way to do it.

     

    with newer versions (2016 sp2 and higher) it is possible on Enterprise edition and with a trace flag to force a query to stop by using Resource Governor - but very dangerous as it affects everything on the particular workgroup. see https://learn.microsoft.com/en-us/sql/t-sql/statements/create-workload-group-transact-sql?view=sql-server-ver16

  • I mean within the SQL itself. Assume something like this fictional code:

    IF (condition...)

    BEGIN

    SET EXECUTION_TIMEOUT=1000

    SELECT * FROM dbo.VeryLargeTable

    -- If the above select-statment takes more than 1000ms it aborts itself and throws an error or something...

     

    END

     

  • oRBIT wrote:

    I mean within the SQL itself. Assume something like this fictional code:

    IF (condition...) BEGIN

    SET EXECUTION_TIMEOUT=1000 SELECT * FROM dbo.VeryLargeTable -- If the above select-statment takes more than 1000ms it aborts itself and throws an error or something...

    END

    I could be wrong but my answer is no... not possible in SQL Server.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply