MySQL查询错误,IF,END IF

时间:2013-10-23 14:16:36

标签: mysql if-statement

我在使用IF,END IF

的MySQL查询中遇到问题

我做了这样的代码:

SET @columnCnt = 1;
SET @indexCnt = 1;
SET @dataCnt = (SELECT COUNT(*) FROM `test`);
WHILE @indexCnt < @dataCnt DO
    IF @indexCnt != @columnCnt THEN
            IF (SELECT COUNT(*) FROM `test` WHERE `idx` = @columnCnt) > 0 THEN
                    UPDATE `test` SET `idx` = @indexCnt WHERE `idx` = @columnCnt;
                    @indexCnt = @indexCnt + 1;
            END IF;
    END IF;

    @columnCnt = @columnCnt+1;
END WHILE;

我得到这样的错误。

MySQL Message :
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHILE @indexCnt < @dataCnt DO
    IF @indexCnt != @columnCnt THEN
            IF ' at line 1

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情;

SET @columnCnt = 1
SET @indexCnt = 1
SET @dataCnt = (SELECT COUNT(*) FROM `test`)
WHILE (@indexCnt < @dataCnt)
Begin
    IF @indexCnt <> @columnCnt 
    Begin
            IF (SELECT COUNT(*) FROM `test` WHERE `idx` = @columnCnt) > 0 
            Begin
                    UPDATE `test` SET `idx` = @indexCnt WHERE `idx` = @columnCnt
                    SET @indexCnt = @indexCnt + 1;
            End
    End

   SET @columnCnt = @columnCnt+1
End