How to set multiple values inside an if else statement?
If you have more than one statement in a if condition, you must use the BEGIN ... END
block to encapsulate them.
IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10)
BEGIN
SET @test1 = 'test1'
SET @test2 = 'test2'
END
ELSE
BEGIN
SET @test1 = 'testelse'
SET @test2 = 'testelse'
END
Use BEGIN
and END
to mark a multi-statement block of code, much like using {
and }
in other languages, in which you can place your multiple SET
statements...
IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10)
BEGIN
SET @test1 = 'test1'
SET @test2 = 'test2'
END
ELSE
BEGIN
SET @test1 = 'testelse'
SET @test2 = 'testelse'
END
Or, use SELECT
to assign values to your variables, allowing both to be assigned in a single statement and so avoid requiring the use of BEGIN
and END
.
IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10)
SELECT
@test1 = 'test1',
@test2 = 'test2'
ELSE
SELECT
@test1 = 'testelse',
@test2 = 'testelse'
The behavior makes sense since your first trial will be split like this:
IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10)
SET @test1 = 'test1'
SET @test2 = 'test2'
ELSE
SET @test1 = 'testelse'
and ELSE
will fail since it does not belong to any IF statement.
Consider doing like this:
IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10)
BEGIN
SET @test1 = 'test1'
SET @test2 = 'test2'
END
ELSE
BEGIN
SET @test1 = 'testelse'
SET @test2 = 'testelse'
END
If you have multiple statements after the IF
you have to use begin
and end
(similar to accolades in c#, for example).
IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10)
BEGIN
SET @test1 = 'test1'
SET @test2 = 'test2'
END
ELSE
BEGIN
SET @test1 = 'testelse'
SET @test2 = 'testelse'
END