Thursday, February 16, 2012

Catching a General Exception

I am trying to write a query that I only want to run on sql server 2005 databases. If a server isn't 2005, it will throw an exception. I would like to catch this general exception. Here is the query...

DECLARE @.Server [nchar] (100)
SET @.Server = (CONVERT(char(100), (SELECT SERVERPROPERTY('Servername'))))

INSERT INTO [tempdb].[dbo].[User_Auditing] (Server, UserName, WinAuth, SQL_Auth_UserName, PassPolicyOn)
SELECT @.Server, s.name, isntuser, q.name, is_policy_checked
FROM sys.syslogins s FULL OUTER JOIN sys.sql_logins q
ON (s.name = q.name)

The errors I would get are as follows...

Msg 208, Level 16, State 1, Line 4
Invalid object name 'sys.syslogins'.
Msg 208, Level 16, State 1, Line 4
Invalid object name 'sys.sql_logins'.

I know in Java, I would just put a try before the declare and a catch("Invalid object name") after the statement, however, I'm not sure if this is even possible in T-SQL. Thanks for any help.
-Kyle

Nope. You cannot. 2005 introduces the concept of try...catch, but it wouldn't catch this error.

You could do something like

if @.@.version like 'Microsoft SQL Server 2005%'

exec ('select ''this is 2005''')

else

exec ('select ''this is NOT 2005''')

I used @.@.version since it will work on any version of SQL Server. Using serverproperty() is another possibilty.

No comments:

Post a Comment