SQL TRY-CATCH and the missing columns

点点圈 提交于 2021-02-07 19:43:34

问题


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?


回答1:


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



回答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.



来源:https://stackoverflow.com/questions/12816539/sql-try-catch-and-the-missing-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!