3

I have the following (SQL Server 2005)

DECLARE @L_ID_FOO_BAR INT
BEGIN TRY
 SELECT @L_ID_FOO_BAR = IDFOO 
 FROM BAR
 WHERE IDFOO = 5
END TRY
BEGIN CATCH
 SELECT @L_ID_FOO_BAR = NULL
END CATCH

in the BAR table I could have (on old databases) or not (in some more recennt databases) the IDFOO column. So, for the missing IDFOO column I'd like to leave @L_ID_FOO_BAR = NULL, in case if that column exists select the respective IDFOO.

However, when executing the script on bases without that column I obtain:

Invalid column name: 'IDFOO'

I already surrounded the script with

IF EXISTS(SELECT 1 FROM SYSCOLUMNS 
WHERE ID = OBJECT_ID('BAR') AND NAME = 'IDFOO') 

but this didn't help, it complains about the invalid column...

Questions
a) What to do to make work this script on both databases, with or without that column?
b) Why does try-catch not hide the invalid column error?

asked Oct 10, 2012 at 9:53

2 Answers 2

8

Question (b) is easier to answer - what you are facing there is a compile-time check, which trumps TRY-CATCH which work at run-time.

For (a)

DECLARE @L_ID_FOO_BAR INT;
DECLARE @SQL NVARCHAR(MAX) = '
 SELECT @L_ID_FOO_BAR = IDFOO 
 FROM BAR
 WHERE IDFOO = 5';
BEGIN TRY
 EXEC sp_executesql @SQL, N'@L_ID_FOO_BAR INT output', @L_ID_FOO_BAR output;
END TRY
BEGIN CATCH
 SELECT @L_ID_FOO_BAR = NULL -- redundant? it starts with NULL
END CATCH
answered Oct 10, 2012 at 10:00
Sign up to request clarification or add additional context in comments.

2 Comments

little fix: DECLARE @SQL NVARCHAR(MAX) *SET @SQL=...*
egads.. 2005. How did I miss that :)
2

I would check syscolumns or information_schema for the existence of the column, then build a dynamic sql query that you then execute with sp_executesql with or without the missing column.

answered Oct 10, 2012 at 9:57

1 Comment

Create a view on the old databases that mimics the missing field then.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.