简体   繁体   中英

SQL Server: if column exists; invalid column name

I need to write a query that will run on different versions of a database. Some of them have a column named Delflag and some don't. If the column exists, it should be included in the select statement and the WHERE clause.

I tried it with the following code:

IF EXISTS 
(
    SELECT * 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE table_name = 'Bericht'
    AND column_name = 'DelFlag'
)
...
ELSE
...

In the IF block, I included the column. In the ELSE block it is not mentioned. However, if the column doesn't exist, I just get the an error "Msg 207 - invalid column name". I checked that the column name is only included in the IF EXISTS block.

I tried to select and filter a column if it exists and if not just leave the part out. I expected the query to run on different databases where the column sometimes exists, sometimes not. If the column exists, it runs, but if it doesn't exist, the query throws

Msg 207
Invalid column name

The query is failing at the binding stage as a column you are referencing doesn't exist.

You are going to have use dynamic sql to build a string based on your logical check and then execute the resulting string using sp_executesql

This would look something like

DECLARE @sql NVARCHAR(MAX) = 'SELECT ColumnA, ColumnB';

IF EXISTS 
(
    SELECT * 
    FROM   INFORMATION_SCHEMA.COLUMNS 
    WHERE  table_name = 'Bericht' AND 
           column_name = 'DelFlag'
)
BEGIN
    SET @sql += ', DelFlag';
END

SET @sql += ' FROM Bericht;';

EXEC sp_executesql @command = @sql;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM