Categories
SQL

Commenting with Care

Comments are a wonderful thing whether it’s keeping track of your thoughts in a drawn out stored procedure, or leaving some breadcrumbs to follow when revisiting code in the future. There is, however, a slightly uglier side to these when you’re trying to look at queries as they run.

Let’s suppose we’re running a very basic script against the server and we’ve been nice enough to comment one of the filters for clarity:

SELECT *
FROM sys.tables
WHERE type = 'U'		-- Only show user tables
AND name = 'Users'

Depending on how we interrogate the running of this script it could be viewed in different ways. For example if we’re using the input buffer and querying our session (ID 67 in this case):

SELECT event_info
FROM sys.dm_exec_input_buffer(67, null)

The results we’ll get returned from this will be showing something with slightly different intent than our original query:

SELECT *  FROM sys.tables  WHERE type = 'U'  -- Only show user tables  AND name = 'Users'

Hmm well that’s not quite what we put in there did we…

This is why I’ve been changing my style to use comment blocks instead so when we run the same exercise the results come back ever so slightly different:

SELECT *  FROM sys.tables  WHERE type = 'U'  /* Only show user tables */  AND name = 'Users'

Now that’s looking much better isn’t it!

Of course it will depend on how you’re looking at these queries and what monitoring tools you’re using. If you’re using the fantastic sp_whoisactive script for example, this will actually provide you a link to open a new tab containing the script formatted correctly:

Who Is Active Results

It’s certainly not something I run up against frequently but I’ve seen issues come up MySQL and SQL Server from time to time so thought it was something worth sharing.

Leave a comment