views:

1167

answers:

4

I just want to verify that I'm not missing something here... so bear with me.

I'm rewriting a lot of old stored procedures and keep seeing IF statements formatted similar to this:

begin
    if @someParameter <> 'ThisType'
    set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'
end

So the Begin...End block just wraps (but does not effect) the IF statement, right? Is this some older syntax for IF or something?

The guy who wrote this didn't have a lot of SQL experience prior to this job; he worked mostly in VB (pre-.NET). Maybe this is syntax from some other language, so he accidentally wrote it this way (by habit)?

This is SQL Server 2005 (code was written on/for SQL Server 2000), btw

Like I said, I'm just trying to wrap my brain around this spaghetti. Any thoughts/comments/illuminating insights are welcome

Thanks

+3  A: 

Correct. The begin...end block in your example encapsulates the IF statement, but does not affect it. Though the guilty programmer probably should have done

BEGIN
  if ... BEGIN
    set @somecode...
  END
END
Dave Markle
+1  A: 

You can safely change it to:

if @someParameter <> 'ThisType'
begin
    set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'
end

begin..end is still extra, but the code is more readable.

dmajkic
+1  A: 

It depends on what's before that. The code you've posted is the same as

if @someParameter <> 'ThisType'
set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'

There could be a statement before the if that requires a begin/end block though.

Jon
Good thought, but nothing relevent before the BEGIN. It's a discreet block
David J
+4  A: 

In T-SQL Begin and END should wrap the contained statements of an IF (or other control structure) with multiple statements being executed (like a code block)

Would Work

if @someParameter <> 'ThisType'
    set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'

Would Also Work but not strictly necessary

if @someParameter <> 'ThisType'
Begin
    set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'
End

Would work as expected

if @someParameter <> 'ThisType'
Begin
    set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'
    {...do other stuff}
End

Would not work as expected (if you expected the both statements to only execute if the IF condition is me)

if @someParameter <> 'ThisType'
    set @someCode = right(cast(@pYear as varchar(6)),2) + 'THIS'
    {...do other stuff}

No semantic value

Begin --without wrapping control structure
    {...stuff}
End
cmsjr