Select columnValue if the column exists otherwise null

前端 未结 3 873
后悔当初
后悔当初 2020-12-14 06:00

I\'m wondering if I can select the value of a column if the column exists and just select null otherwise. In other words I\'d like to \"lift\" the select statement to handl

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 06:45

    You cannot do this with a simple SQL statement. A SQL query will not compile unless all table and column references in the table exist.

    You can do this with dynamic SQL if the "subquery" is a table reference or a view.

    In dynamic SQL, you would do something like:

    declare @sql nvarchar(max) = '
    SELECT uniqueId, columnTwo, '+
        (case when exists (select *
                           from INFORMATION_SCHEMA.COLUMNS 
                           where tablename = @TableName and
                                 columnname = 'ColumnThree' -- and schema name too, if you like
                          )
              then 'ColumnThree'
              else 'NULL as ColumnThree'
         end) + '
    FROM (select * from '+@SourceName+' s
    ';
    
    exec sp_executesql @sql;
    

    For an actual subquery, you could approximate the same thing by checking to see if the subquery returned something with that column name. One method for this is to run the query: select top 0 * into #temp from () s and then check the columns in #temp.

提交回复
热议问题