• Hugo Kornelis (2/14/2012)


    Koen Verbeeck (2/14/2012)


    kll 51891 (2/14/2012)


    I would have expected it to fail due to no newline or semicolon.

    But it were not so

    Anywhere I can find specific rules about when to use and when not to use semicolon?

    Except the reserved word ";with" of course.

    The semicolon is not yet obligated, except when using the WITH clause. This probably will change in a future version.

    If there's a statement before the WITH clause, it should be terminated with a semicolon. Pay attention, this is not the same as saying that it should be ";WITH". If everyone starts terminating statements with semicolon in old code to make the code portable to a newer edition of SQL Server, all ;WITH statements will fail.

    Most of the above is true.

    Terminiating SQL statements with a semicolon has always been allowed in SQL Server, but it was optional. WITH was the first keyword (but is not the only one) that requires the statement before it (if any) to be semicolon-terminated, otherwise the parser would think that the WITH keyword was for query hints. It has already been announced that in some future version, omitting the semicolon will be disallowed in all cases. There has not been any mention as to which version that will be. But it's a good idea to start getting into the habit now of always using the semicolon statement terminator.

    I consider the use of ;WITH a bad habit, as it works around one limitation while not addressing the true underlying issue. And it will come back to bite you when terminating is no longer optional. However, it does currently work - not because he parser accepts prepending WITH with a semicolon as a viable alternative, but because the parser ignores whitespace and line breaks - so it "sees" the semicolon right after the end of the preceding statement and interprets it as a statement terminator.

    I also consider ;WITH a bad habit because it already breaks things. If you use WITH a lot, and get in the habit of prepending the semicolon, chances are you'll end up writing code like the following:

    CREATE VIEW v_sample AS

    ;WITH a AS ...

    which will not execute because the semicolon terminates the CREATE VIEW statement before it's complete. Sure, that's easy to fix, but if you're in the habit of prepending the semicolon, you'll have to fix it every time. If, on the other hand, you get in the habit of terminating statements with the semicolon instead, you won't have anything to fix.