Select columnValue if the column exists otherwise null

前端 未结 3 866
后悔当初
后悔当初 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 07:05

    As others already suggested, the sane approach is to have queries that meet your table design.

    There is a rather exotic approach to achieve what you want in (pure, not dynamic) SQL though. A similar problem was posted at DBA.SE: How to select specific rows if a column exists or all rows if a column doesn't but it was simpler as only one row and one column was wanted as result. Your problem is more complex so the query is more convoluted, to say the least. Here is, the insane approach:

    ; WITH s AS
      (subquery)                                    -- subquery
    SELECT uniqueId
        ,  columnTwo
        ,  columnThree =
           ( SELECT ( SELECT columnThree 
                      FROM s AS s2
                      WHERE s2.uniqueId = s.uniqueId
                    ) AS columnThree
             FROM (SELECT NULL AS columnThree) AS dummy
           )
    FROM s ;
    

    It also assumes that the uniqueId is unique in the result set of the subquery.

    Tested at SQL-Fiddle


    And a simpler method which has the additional advantage that allows more than one column with a single subquery:

    SELECT s.*     
    FROM
        ( SELECT NULL AS columnTwo,
                 NULL AS columnThree,
                 NULL AS columnFour
        ) AS dummy 
      CROSS APPLY
        ( SELECT 
              uniqueId,
              columnTwo,
              columnThree,
              columnFour
          FROM tableX
        ) AS s ;
    

    The question has also been asked at DBA.SE and has been answered by @Andriy M (using CROSS APPLY too!) and Michael Ericsson (using XML):
    Why can't I use a CASE statement to see if a column exists and not SELECT from it?

提交回复
热议问题