One way to do this is to check for the columns existence, then build the Dynamic SQL based on whether that column exists or not.
Without Dynamic SQL, SQL Server will attempt to evaluate whether or not the column exists before it even executes the statment, resulting in an error.
It does, however, mean you will have 2 queries to write and potentially alter in future. But I don't believe you should really be targeting SELECT
statements on columns that may not exist.
declare @SQL varchar(max)
If exists (select 1 from sys.columns where Name = N'NameOfColumn' and object_id=object_id(N'yourTableName'))
begin
set @SQL = 'select ID, NameOfColumn from yourTableName'
exec(@sql)
end
else
begin
Print 'Column does not exist'
end
CASE
statement. – Mark Sinkinson yesterdayINFORMATION_SCHEMA
could work as a workaround. – Brilliand yesterday