SQL IF ELSE BEGIN END

If there are no start or end statements in sql, the next statement is the only one that will be executed if the if condition is true ... in the case below, is it possible that the insert statement will also be executed if the condition is true?

IF (a > 1) SET @b = 1 + 2 INSERT INTO #F (a, b, c) VALUES (1, 2, 3) 
+4
source share
6 answers

The insert statement will be called in all cases regardless of the if clause, since the if clause will be only one line

if you are not sure, add a beginning and an end (in fact, I always add a beginning and an end, even if this is one line with which you never know when you or someone else will need to add another line)

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

TSQL has a Begin / End clause.

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

"If there are no start and end statements in sql, the next statement is the only one that will be executed if the if condition is true."

I'm not sure if this is true, but why not just wrap it at the beginning / end and not worry about it?

+1
source

Try the following:

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

In your example, the insert statement will ALWAYS be executed, since it is 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' 

This is 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' 
0
source

All Articles