USE statement with TRY / CATCH

  • I'm executing some TSQL code in a job step. I need to specify the master database in the Database drop-down than what needs to be referenced in the code.

    If I put a USE statement before a TRY / CATCH, does the specified database scope carry on through the TRY / CATCH.

    For example:

    USE TestDB

    GO

    BEGIN TRY

    SET NOCOUNT ON

    --Write all dirty pages to disk before shrinking the log file

    CHECKPOINT

    DBCC SHRINKFILE(TestDB_Log)

    END TRY

    BEGIN CATCH

    DECLARE @ErrorMessage NVARCHAR(300)

    SET @ErrorMessage = N'Error Line ' + CAST(ERROR_LINE() AS VARCHAR(5)) + ': ' + ERROR_MESSAGE()

    RAISERROR (@ErrorMessage,

    16, -- Severity.

    1 -- State.

    ) WITH LOG

    END CATCH

  • hindle.steve (10/20/2011)


    I'm executing some TSQL code in a job step. I need to specify the master database in the Database drop-down than what needs to be referenced in the code.

    If I put a USE statement before a TRY / CATCH, does the specified database scope carry on through the TRY / CATCH.

    For example:

    USE TestDB

    GO

    BEGIN TRY

    SET NOCOUNT ON

    --Write all dirty pages to disk before shrinking the log file

    CHECKPOINT

    DBCC SHRINKFILE(TestDB_Log)

    END TRY

    BEGIN CATCH

    DECLARE @ErrorMessage NVARCHAR(300)

    SET @ErrorMessage = N'Error Line ' + CAST(ERROR_LINE() AS VARCHAR(5)) + ': ' + ERROR_MESSAGE()

    RAISERROR (@ErrorMessage,

    16, -- Severity.

    1 -- State.

    ) WITH LOG

    END CATCH

    Yes, you can do this. But you don't have to change databases to do that.

    Converting oxygen into carbon dioxide, since 1955.
  • hi,

    if you use

    USE TestDB

    GO

    there is no need to select any databases from the Database list the query is going to execute under TestDB only

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

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