如何在if else语句中设置多个值?

时间:2016-03-29 08:56:17

标签: sql sql-server tsql

我正在尝试在下面的if else语句中设置多个值,如果我设置了一个值,但是如果我设置了两个值,则它不起作用:

DECLARE @test1 varchar(60);
DECLARE @test2 varchar(60);


IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10)
SET @test1 = 'test1'
SET @test2 = 'test2' 
ELSE
SET @test1 = 'testelse'
SET @test2 = 'testelse'
  

错误消息:“消息156,级别15,状态1,行9”   关键字'ELSE'附近的语法不正确。“

然而,似乎可以在else之后有多个SET变量;这段代码有效:

IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10)
SET @test1 = 'test1'
ELSE
SET @test1 = 'testelse'
SET @test2 = 'testelse'

我该如何正确地做到这一点?

5 个答案:

答案 0 :(得分:42)

如果在if条件中有多个语句,则必须使用BEGIN ... END块来封装它们。

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

答案 1 :(得分:5)

使用BEGINEND标记多语句代码块,就像在其他语言中使用{}一样,您可以在其中放置多个SET陈述......

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

或者,使用SELECT为变量分配值,允许在一个语句中分配两者,因此请避免使用BEGINEND

IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10)
    SELECT
        @test1 = 'test1',
        @test2 = 'test2' 
ELSE
    SELECT
        @test1 = 'testelse',
        @test2 = 'testelse'

答案 2 :(得分:2)

如果您在IF之后有多个语句,则必须使用beginend(例如,类似于c#中的荣誉)。

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

答案 3 :(得分:1)

这种行为是有道理的,因为你的第一次审判会像这样分开:

IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10)
SET @test1 = 'test1'

SET @test2 = 'test2' 

ELSE
   SET @test1 = 'testelse'

ELSE将失败,因为它不属于任何IF语句。

考虑这样做:

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

答案 4 :(得分:0)

你问题中的第二个表达式总是会导致执行 @ test2 =' testelse' 因为ELSE在else之后的第一个表达式之后结束:

IF ((SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10)
SET @test1 = 'test1'
ELSE
SET @test1 = 'testelse'
-- IF is done evaluating here
SET @test2 = 'testelse' 

如果IF中有多个表达式,则始终可以使用BEGIN / END对表达式进行分组。

但在你的情况下,最简单的方法是:

IF (SELECT COUNT(*) FROM table WHERE table.Date > '2016-03-20') > 10
  SELECT @test1 = 'test1', @test2 = 'test2' 
ELSE
  SELECT @test1 = 'testelse', @test2 = 'testelse'