I need to select a column only if it exists in table, else it can be set to null.
Sample table below, lets say the marks
col is not necessary be there, so need to be checked 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 should go in line to select marks
?
Syntax. SELECT (optional: any desired columns), CASE WHEN (condition) THEN (desired output) WHEN (other condition) THEN (desired output) ELSE (desired output) END AS (descriptive header for the output column) FROM (appropriate table);
Checking Existence of the Column: For checking the existence we need to use the COL_LENGTH() function. COL_LENGTH() function returns the defined length of a column in bytes. This function can be used with the IF ELSE condition to check if the column exists or not.
When we have to select multiple columns along with some condition, we put a WHERE clause and write our condition inside that clause. It is not mandatory to choose the WHERE clause there can be multiple options to put conditions depending on the query asked but most conditions are satisfied with the WHERE clause.
SQL Doesn't permit that. Your result set has two options:
*
and tbl.*
Perhaps this will suit your needs, SELECT * FROM table1;
You'll always get that column, if it exists.
try this
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With