Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation when Column doesn't exist

I've a Stored procedure which 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 doesn't exist. I don't want to take existence check out of SP. Currently the error is :

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

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

and why for instance if you check for existence table and select non-existent table that works?

like image 743
rakamakafo Avatar asked Mar 12 '23 01:03

rakamakafo


1 Answers

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;
like image 77
Gordon Linoff Avatar answered Mar 21 '23 03:03

Gordon Linoff