Hi @mocres
It seems that the following code is legit in Microsoft SQL Server (tested on v. 2022):
IF (1 > 0)
BEGIN
THROW 50003, 'E3', 16;
END
Your issue with such code seems to be coming from the SQL Server Management Studio editor parser (tested with v.20.1).
In the editor, the following is indeed considered incorrect:
IF (1 > 0)
BEGIN
THROW 50003, 'E3', 16; // Error: Incorrect syntax near 'THROW'.
^^^^^
END
However, if I send this command to the SQL Server for parse, it gets parsed and executed successfully!
On the server side, at no point does it give a parse error.
Commands completed successfully.
Completion time: 2024-04-22T14:08:38.6390295+02:00
Msg 50003, Level 16, State 16, Line 3
E3
Completion time: 2024-04-22T14:10:14.3681738+02:00
This is actually not inconsistent with the documentation of THROW that you have linked above (ref):
The statement before the THROW statement must be followed by the semicolon ( ; ) statement terminator.
It’s not inconsistent because BEGIN is not a (full) statement: it’s just the beginning of the statement.
Microsoft seems to have acknowledged the inconsistency between SQL Server and SQL Server Management Studio here. However, the issue in the community seems to have been closed due to a lack of required additional information.
Anyway, given that:
;THROW is used very often in T-SQL code (like ;WITH with Common Table Expressions)
- it is considered idiomatic (see here)
- Microsoft SQL Server Management Studio is the most used tool to interact with SQL Server
We are going to acknowledge its endemic use and change the behavior of S1116 for T-SQL to not report when ; is followed by THROW specifically.
I have created a reproducer in our code base and an issue in our issues tracker, that will be dealt with in one of the next hardening sprints on the T-SQL Analyzer.
Waiting for the issue to be fixed, you can resolve the issue on SonarQube as False Positive.
If you have many THROW statements right after a BEGIN block and the rule becomes noisy, you can also disable it in the quality profile.
Hope it helps,
Best regards,
Antonio