简体   繁体   中英

SQL-Server, TSQL, TRY-CATCH block

I'm having a problem with try/catch error-handling. Let's have a look on my (simple) code:

BEGIN TRY
print 'important'
use myDB1; -- no problem, the myDB1 is in place...
select * from dbo.Tab1;
use myDB2;
--here error, the myDB2 is not there, 
--but error handling doesn't jump into catch-block

select * from dbo.Tab2;
END TRY
BEGIN CATCH
    print 'myDB2 is not there'
END CATCH

I know, I could say:

select * from myDB2.dbo.Tab2 without changing to myDB2, but when I need to check (for example..) if a table has an identity

(((SELECT OBJECTPROPERTY( OBJECT_ID('myDB2.dbo.'+ @TableName), 'TableHasIdentity'))= 1)

I must run this from myDB2, otherwise I'll get a wrong result. So how can I catch the error in the catch-block?

Thanks for your help

Purclot

You need to encapsulate the test condition in an EXEC to get the error to be treated as a run-time issue. You then need to fully-qualify the objects for the queries that hit databases that might not exist so that you can avoid the USE statement. For functions such as OBJECTPROPERTY that require local context, you can use sp_executesql to run queries in a different database context and return a usable result.

DECLARE @TableName SYSNAME,
        @SQL NVARCHAR(MAX),
        @Result BIT

BEGIN TRY

    USE [master];
    SELECT TOP 1 * FROM sys.objects

    SET @TableName = N'sysjobhistory'
    SET @Result = 0
    SET @SQL = N'USE [msdb]; DECLARE @Result BIT;
                 SET @TempResult = OBJECTPROPERTY( OBJECT_ID(N''' + @TableName +
                 N'''), ''TableHasIdentity'')'

    EXEC sp_executesql @SQL,
                       N'@TempResult BIT OUTPUT',
                       @TempResult = @Result OUTPUT

    SELECT @Result AS [ResultThatCanBeUsedLocally]

    EXEC('USE [NotHere];')

    SELECT TOP 1 * FROM NotHere.sys.objects

END TRY
BEGIN CATCH

    PRINT 'Error!!'
    PRINT ERROR_MESSAGE()

END CATCH

After some chatty comments OP just needs to know if table got a identity. You can use it to list tables without identity in a given database

SELECT TABLE_NAME
FROM MyDB2.INFORMATION_SCHEMA.TABLES
WHERE Table_NAME NOT IN (
    SELECT c.TABLE_NAME
    FROM MyDB2.INFORMATION_SCHEMA.COLUMNS c
    INNER JOIN MyDB2.sys.identity_columns ic ON c.COLUMN_NAME = ic.NAME
)
AND TABLE_TYPE = 'BASE TABLE'

EDIT

after some more chat and digging I found OP really wants to switch DB inside a try catch block. But that object existence is checked at parse time and a try catch ill work only on run time errors. Also object missing errors appear to not get the necessary severity to be caught by the try catch block (and even using a full qualified name ill not to work)

OP must rethink how he can accomplish the task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM