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)
IF (a > 1)
BEGIN
SET @b = 1 + 2
INSERT INTO #F (a, b, c) VALUES (1, 2, 3)
END
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)
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
"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?
Try this:
IF (A > 1)
BEGIN
SET @B = 1 + 2
INSERT INTO #F(a, b, c) VALUES (1, 2, 3)
END
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.