Commenting a branching IF-THEN-ELSE.1
October 19, 2021 by Kenneth Fisher
I’m a big fan of comments (MSSQL, Powershell), so along those lines here’s an interesting way to comment an IF-THEN-ELSE block.
IF SERVERPROPERTY ('ProductMajorVersion') >= 13 IF SERVERPROPERTY ('productlevel') = 'RTM' PRINT 'Patch me!' ELSE -- SERVERPROPERTY ('ProductMajorVersion') >= 13 & SERVERPROPERTY ('productlevel') <> 'RTM' PRINT 'Ok.' ELSE -- SERVERPROPERTY ('ProductMajorVersion') < 13 IF SERVERPROPERTY ('productlevel') = 'RTM' PRINT 'Upgrade me!' ELSE -- SERVERPROPERTY ('ProductMajorVersion') < 13 & SERVERPROPERTY ('productlevel') <> 'RTM' PRINT 'Upgrade me anyway!'
I’ll be honest, it’s not like I do a lot of branching if statements, but it does happen, and when it does, the logic can get rather .. complicated. Particularly if there are more than two branches. Not to mention that there is almost always more than a single short print statement between the IF and the ELSE. Because of that I comment the conditions for the ELSE statement. If it gets really complicated I might even start adding comments to the inner IF statements with the logic from the outer IF statement(s). It’s rare that things are that complicated though. Regardless, this is a great way to help you be certain of your logic. Not to mention the next person who works on this code, particularly if that person is future you.
Category: Microsoft SQL Server, SQLServerPedia Syndication, T-SQL | Tags: comments, Microsoft SQL Server, T-SQL
One thought on “Commenting a branching IF-THEN-ELSE.”
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
I’m a fan of comments too. Others have told me that your code “should” be easy enough to read without them. I find myself using them for CASE statements. If anything, they help you know what you were thinking at the time. Like you, I don’t try and go too deep, but sometimes the real world doesn’t play fair.