views:

397

answers:

7

If there are no begin and end statements in sql, the next statement is the only one that gets executed if the if condition is true...in the case below, is there anyway the insert statement will also get executed if the if condition is true?

 IF (a > 1) 
     SET @b = 1 + 2
 INSERT INTO #F (a, b, c) VALUES (1, 2, 3)
+6  A: 
IF (a > 1)    
   BEGIN
     SET @b = 1 + 2 
     INSERT INTO #F (a, b, c) VALUES (1, 2, 3)
   END
madcolor
You need the Begin End.
madcolor
+1  A: 

There is Begin/End clause in TSQL.

IF (a > 1)
BEGIN 
   SET @b = 1 + 2
   INSERT INTO #F (a, b, c) VALUES (1, 2, 3)
END
Novitzky
+1  A: 

"If there are no begin and end statements in sql, the next statement is the only one that gets executed if the if condition is true"

I'm not sure if that is true, but why not just wrap it in a begin/end and not worry about it?

Gratzy
+1  A: 

Try this:

IF (A > 1)
BEGIN
  SET @B = 1 + 2
  INSERT INTO #F(a, b, c) VALUES (1, 2, 3)
END
Pete OHanlon
+4  A: 

The insert statement will be called in all cases independent of the if clause as the if clause will just be the one line

if you are not certain add the begin and end (actually I always add begin and end as even if it is one line to begin with you never know when you or someone else will need to add another line)

Mark
A: 

In your example, the insert statement will ALWAYS be executed, because it's not evaluated as part of the IF statement.

Sample code for MS SQL Server:

Declare @a as int
Declare @b as int
Set @a = 2
If (@a > 1) Set @b = 1 + 2 Select 'Select Reached'

That's equivalent to writing:

Declare @a as int
Declare @b as int
Set @a = 2
If (@a > 1) 
BEGIN
    Set @b = 1 + 2
END
Select 'Select Reached'
CodeToaster
A: 

Why does this not work: I only want one of these selects to run?

Declare @a as int 
Declare @b as int 
Set @a = 1
If (@a > 1) begin Set @b = 1 + 2 end Select 'Select Reached' 
if (@a <= 1) begin Set @b = 1 + 2 end Select 'Select not Reached'
Chris J