SQL中关于我的if else语句的语法错误

时间:2019-02-23 08:31:59

标签: sql sql-server tsql

我的else语句的语法有误。

这是我的代码

 DECLARE @var VARCHAR(20) = (SELECT TOP 1 name FROM store2)

 DECLARE @i int = 1
 DECLARE @incr int
 DECLARE @y VARCHAR(20)
 WHILE @i < 5
 BEGIN
     SET @y = (SELECT name FROM store1 WHERE id = @i);    
     IF @y = @var
     SET @incr = (SELECT count FROM store1 WHERE id = @i)+1
     PRINT N'TRUE';

     ELSE
     PRINT 'FALSE';



 SET @i = @i + 1
 END

1 个答案:

答案 0 :(得分:1)

通过适当的缩进,错误将变得非常明显:

 DECLARE @var VARCHAR(20) = (SELECT TOP 1 name FROM store2)

 DECLARE @i int = 1
 DECLARE @incr int
 DECLARE @y VARCHAR(20)

 WHILE @i < 5
 BEGIN
     SET @y = (SELECT name FROM store1 WHERE id = @i);    

     IF @y = @var
         SET @incr = (SELECT count FROM store1 WHERE id = @i)+1

     PRINT N'TRUE';

     ELSE
         PRINT 'FALSE';

     SET @i = @i + 1
 END

如果您有IF,则,下一条语句将在该IF块内执行-进一步的语句(包括您的ELSE ... 。)位于IF块之外-除非您向其中添加BEGIN ... END-像这样:

     IF @y = @var
     BEGIN
         SET @incr = (SELECT count FROM store1 WHERE id = @i)+1
         PRINT N'TRUE';
     END
     ELSE
         PRINT 'FALSE';