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.

07 January 2022

Visual Studio - High contrast syntax colors

When Windows is in a high contrast theme, Visual Studio displays all code in the same color. To change this, go to Tools > Options > Environment > Fonts and Colors and select Show settings for Text Editor. Now you can set the colors for identifiers (variable names), (user) type names, strings (text between quotes), literals, numbers, comments etc. This is my setup:

I've put this here so that next time I reinstall Visual Studio, I can refer to this screenshot to remember what colors I used.

Note that the Plain Text foreground is used for the caret's color.