13 January 2022

SQL - check whether or not a column exists

This is a simple way for SQL Server and Sybase databases to check whether a column exists or not inside a query:

COL_LENGTH('Keywords', 'parent_id')

But you can't use that in a select clause. There is another trick though to select a column that may or may not exist:

SELECT (
  SELECT Keyw2.parent_id
  FROM (SELECT 0 AS parent_id) [Dummy]
  CROSS APPLY (SELECT FIRST parent_id FROM dba.Keywords WHERE keyword_id = Keyw.keyword_id) [Keyw2]
  ) [KeywordParent],
  ...
FROM dba.Keywords Keyw

The trick relies on not using a table alias in the subselect!

This can come in handy when columns may or may not exist depending on the application's database version.

No comments:

Post a Comment