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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With