Swami
Swami

Reputation:

SQL IF ELSE BEGIN END

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)

Upvotes: 4

Views: 22552

Answers (6)

Gratzy
Gratzy

Reputation: 9389

"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?

Upvotes: 1

Bob Black
Bob Black

Reputation: 2405

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'

Upvotes: 0

mmmmmm
mmmmmm

Reputation: 32700

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)

Upvotes: 8

Pete OHanlon
Pete OHanlon

Reputation: 9146

Try this:

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

Upvotes: 0

Novitzky
Novitzky

Reputation: 4876

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

Upvotes: 1

madcolor
madcolor

Reputation: 8170

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

Upvotes: 8

Related Questions