Select columnValue if the column exists otherwise null

前端 未结 3 870
后悔当初
后悔当初 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:53

    you can use dynamic SQL.

    first you need to check exist column and then create dynamic query.

    DECLARE @query NVARCHAR(MAX) = '
    SELECT FirstColumn, SecondColumn, '+
      (CASE WHEN exists (SELECT 1 FROM syscolumns 
      WHERE name = 'ColumnName' AND id = OBJECT_ID('TableName'))
          THEN 'ColumnName'
          ELSE 'NULL as ThreeColumn'
       END) + '
    FROM TableName'
    
    EXEC sp_executesql @query;
    

提交回复
热议问题