2

I have the below sample code. Assuming I do not know if a particular column exists in a table or not, how could I write the query in a way that I can default the column value to 'Not available' if the column doesn't exist in the table?

Example:

select COL1, COL2,
CASE
    WHEN OBJECT_ID('COL3') IS NULL THEN 'Not Available'
    ELSE COL3
END AS COL3
from TABLE1

Thanks in advance.

5
  • You can't really do this with regular SQL, and in fact I'm pretty sure your above statement won't even compile unless COL3 already really exists. Commented Jun 26, 2020 at 10:49
  • yes this sql doesnt work, its just to illustrate what i am trying to achieve here. Commented Jun 26, 2020 at 10:49
  • You can probably do this from a stored procedure. Commented Jun 26, 2020 at 10:50
  • Simply select * from table1? Commented Jun 26, 2020 at 10:51
  • 1
    You would need to use dynamic SQL for this since a query that references a non-existent column will not compile. But I think you have larger issues if the schema is unknown at run time. Commented Jun 26, 2020 at 10:52

1 Answer 1

1

This is quite tricky to do (without dynamic SQL), but there is a way by playing with the scoping rules in SQL. You can do this assuming you have a unique or primary key in the table:

select t1.col1, t1.col2,
       (select col3                               -- no alias!
        from table1 tt1
        where tt1.id = t1.id                      -- the primary/unique key
       ) col3 
from table1 t1 cross join
     (values ('Not Available')) v(col3)           -- same name

The subquery will fetch col3 from the table1 in the subquery if it exists. Otherwise it will reach out and find col3 from the values() clause.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.