0

我在使用 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

我怎么解决这个问题?

4

1 回答 1

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
于 2013-10-23T15:26:48.410 回答