I would like to perform a SELECT where it selects a column value only if that column exists in the table, otherwise null is displayed.
This is what I am doing now:
SELECT TOP 10 CASE WHEN EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA ='test' and TABLE_NAME='tableName' and COLUMN_NAME='columnName') THEN columnName ELSE NULL END AS columnName
I also tried this:
SELECT TOP 10 CASE WHEN (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA ='test' and TABLE_NAME='tableName' and COLUMN_NAME='columnName') >0 THEN columnName ELSE NULL END AS columnName
Both of them work well if the column is present in the table. But when there is no column, it gives me an error:
Invalid column name 'columnName'
source share