Compilation when the column does not exist

I have a stored procedure that looks like this:

create procedure test as
begin
if  exists(
               select 1 from sys.columns 
                where Name      = N'Column2'
                  and Object_ID = Object_ID(Table2')
              )

select Column2 from Table2
end

I want to run this procedure on db where Column2 does not exist . I do not want to verify the existence of SP. Currently error:

Msg 207, Level 16, State 1, Test Procedure, Line 39 [Batch Start Line 0] Invalid column name "Column2".

Is there any way to do this? Why yes and why not?

and why, for example, if you check the existence table and select a nonexistent table that works?

+4
source share
1 answer

Use dynamic SQL:

create procedure test as
begin
    if exists (select 1
               from sys.columns 
               where Name = N'Column2' and Object_ID = Object_ID('Table2')
              )
    begin
        exec sp_executesql N'select Column2 from Table2';
    end;
end;
+7
source

Source: https://habr.com/ru/post/1655495/


All Articles