SQL - conditionally select column if exists

I need to select a column only if it exists in the table, otherwise it can be set to null.

The example table below, let's say that markscol is not necessarily there, so you need to check if it exists

Table1

name marks
joe  10
john 11
mary 13

Query:

select
    name,
    marks if it exists else null as marks1 -- pseudo code
from 
    table1

What needs to be done to choose marks?

+4
source share
3 answers

SQL This does not allow. There are two options in your result set:

  • Static inclusion
  • All from a table or subquery through a column extension using *andtbl.*

Perhaps this will suit your needs, SELECT * FROM table1;you will always get this column, if one exists.

+5

:

IF EXISTS( SELECT 1
           FROM information_schema.columns 
           WHERE table_name='your_table' and column_name='your_column') THEN
   SELECT your_column as 'some_column'
ELSE
   SELECT NULL as 'some_column'
END IF
0

IF COL_LENGTH('your_table_name','column_name_you_want_to_select') IS NULL BEGIN 
 --This means columns does not exist or permission is denied
 END
 else 
 --Do whatever you want
0

Source: https://habr.com/ru/post/1663046/


All Articles