开发者

SQL Conditional Column Existence

开发者 https://www.devze.com 2023-01-28 22:27 出处:网络
Can I somehow select a column if exists in a view, but ignore the column if it does not exist? SELECT CASE

Can I somehow select a column if exists in a view, but ignore the column if it does not exist?

SELECT
    CASE
        WHEN EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MyView' AND COLUMN_NAME = 'MyColumn')
            THEN MyView.MyColumn
        ELSE NULL
    END AS [Sometimes]
FROM
    MyView

Rig开发者_JAVA技巧ht now, that returns a "Msg 207 Invalid column name" error.

Perhaps some option to ignore that error is possible?


You can do it by using dynamic SQL:

declare @sql varchar(200)   
IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MyView' AND COLUMN_NAME = 'MyColumn') 
BEGIN
    select  @sql = "SELECT Column1m Column2, MyColum from MyView"
END
ELSE
BEGIN
    select  @sql = "SELECT Column1m Column2, null as MyColum from MyView"
END 

-- executes dynamic sql
EXEC @sql


No, this isn't possible. The column-access has to be compiled, if nothing else, and this happens before the expression that suppresses it is evaluated. You need to generate SQL on-the-fly for this.


The best you can do is

if EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MyView' AND COLUMN_NAME = 'MyColumn')
Select MyView.MyColumn from MyView
else
Select NULL MyColumn 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号