Is it necessary to include "BEGIN" and "END" statements in a SQL script?

valmatic
valmatic used Ask the Experts™
on
Hi.  A programmer came in and helped us generate a lot of SQL code.  I'm a novice SQL user but I can follow along and decipher what steps are being performed so am reviewing to understand the general flow of the application better.  I noticed that in many places the programmer did not use BEGIN and END statements, while in other places, they are being used.  Is this just good syntax or are these statements required to perform some functions while others, not so much?  A couple of the Sprocs with these statements included are simply calling out table updates but same thing is happening in another sproc and the begin/end statement are not used.  thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Database Administrator
Top Expert 2005
Commented:
A stored procedure does not require an outer BEGIN/END statement.  There is not harm in adding them to a stored procedure but they aren't necessary.  It comes down to local coding standards and personal preference really.

However, a user-defined function DOES require a BEGIN & END.

Within a procedure, say for an IF statement you must include a BEGIN/END if there is more than one statement associated with the conditional.  They are not necessary but good practice to always have a BEGIN/END even for a single statement.

i.e.

IF (@A = @B)
BEGIN
   -- do something
END

is equivalent to

IF (@A = @B)
   --do something
Jim HornSQL Server Data Dude
Most Valuable Expert 2013
Author of the Year 2015
Commented:
In addition to the above correct answer couple of other places too, such as cursors and WHILE loops, but not many.
Doug BishopDatabase Developer
Commented:
No points please, but to expand on Brian's comment, the reason it is good practice around an IF statement is to make sure you don't break logic if another statement is subsequently added. It is clear that it belongs inside the IF block. If you start with:

IF (@A = @B)
   SET @B = @B + 1
SET @A = @A - 1

@B will be incremented only if @A and @B are equal and @A will ALWAYS be decremented. Using BEGIN/END makes it clear exactly what should be associated with the IF statement.

Author

Commented:
Thanks so much for the quick responses.  Exactly what I wanted to know for my own growing knowledge.  
Bishop, I know you said no points but it's just good form man..  Plus your insight is great.  :)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial