Switchkick
Switchkick

Reputation: 2796

Are BEGIN/END needed in SQL script?

Are BEGIN/END needed in SQL scripts (in general) or is it fine to replace them with { and }

Example:

IF DB_ID('comics') IS NOT NULL        
    BEGIN
        PRINT 'Database exists - dropping the comics database.';
        DROP DATABASE comics;
    END

VS

IF DB_ID('comics') IS NOT NULL        
{
    PRINT 'Database exists - dropping the comics database.';
    DROP DATABASE comics;
}

I am using MS SQL Server 2008 R2

Upvotes: 1

Views: 1989

Answers (3)

Greg Hewgill
Greg Hewgill

Reputation: 994281

The documentation for IF...ELSE shows:

IF Boolean_expression 
     { sql_statement | statement_block } 
[ ELSE 
     { sql_statement | statement_block } ] 

However, the Transact-SQL Syntax Conventions (Transact-SQL) page shows:

{ } (braces)    Required syntax items. Do not type the braces.

So, the braces aren't something that you can enter in your code, but instead are simply showing that there is exactly one sql_statement or statement_block required in an IF statement. (Of course, a statement_block can contain multiple sql_statements as long as you use BEGIN and END around them.)

Upvotes: 2

eugenesqr
eugenesqr

Reputation: 579

Never heard about {} in SQL. SQL 92 specification uses BEGIN END. I think BEGIN END is the only option.

Upvotes: 1

mgiuffrida
mgiuffrida

Reputation: 3579

You should use BEGIN...END for statement blocks. Source

Upvotes: 2

Related Questions