2011-07-19 51 views
2

我有一個MySQL存儲過程,並在其中包含以下WHILE語句。使用IF/THEN/ELSE的MySQL存儲過程

我已經確認@RowCnt是1,@MaxRows是6090,但是經過進一步調試後,我意識到WHILE語句正在經歷一次迭代而不是繼續;所以我希望能夠解釋一下可能會導致這種情況的原因。

完全披露:我從SQL Server移植到MySQL存儲過程,這是我以前從未採取過的。 (意爲SQL服務器,移植或存儲過程..)

WHILE @RowCnt <= @MaxRows DO 
    SELECT @currentReadSeq:=ReadSeq, @currentReadStrength:=ReadStrength, @currentReadDateTime:=ReadDateTime, @currentReaderID:=ReaderID FROM tblTempRead WHERE rownum = @RowCnt; 

    IF (((@lastReadSeq + 10) > @currentReadSeq) AND (@lastReaderId = @currentReaderId)) THEN 
     SET @lastReadSeq = @currentReadSeq, @lastReadStrength = @currentReadStrength, @lastReadDateTime = @currentReadDateTime, @lastReaderID = @currentReaderID; 
    ELSE 
     INSERT INTO tblreaddataresults (SiteID, ReadDateTimeStart, ReadDateTimeEnd, ReadSeqStart, ReadSeqEnd, ReaderID, DirectSeconds) VALUES ('1002', @saveReadDateTime, @lastReadDateTime, @saveReadSeq, @lastReadSeq, @lastReaderID, timestampdiff(SECOND,@saveReadDateTime,@lastReadDateTime)); 

     SET @saveReadSeq = @currentReadSeq, @saveReadStrength = @currentReadStrength, @saveReadDateTime = @currentReadDateTime, @saveReaderID = @currentReaderID; 

     SET @lastReadSeq = @saveReadSeq, @lastReadStrength = @saveReadStrength, @lastReadDateTime = @saveReadDateTime, @lastReaderID = @saveReaderID; 
    END IF; 

    SET @RowCnt = @RowCnt+1; 
END WHILE; 
+0

嘗試建立一個'繼續handler',看看你的查詢提供了一個錯誤,如果這是引發你知道什麼是錯的。 http://dev.mysql.com/doc/refman/5.0/en/declare-handler.html您可以通過插入虛表來調試SP調用。 – Pentium10

+0

WHILE正在運行一次,並且在IF語句下面敲擊SET。運行一次後退出。 – erbaker

回答

2

試試這個構建

WHILE (@RowCnt <= @MaxRows) 
BEGIN 
    SELECT @currentReadSeq:=ReadSeq, @currentReadStrength:=ReadStrength, @currentReadDateTime:=ReadDateTime, @currentReaderID:=ReaderID FROM tblTempRead WHERE rownum = @RowCnt; 

    IF (((@lastReadSeq + 10) > @currentReadSeq) AND (@lastReaderId = @currentReaderId)) 
     BEGIN 
     SET @lastReadSeq = @currentReadSeq, @lastReadStrength = @currentReadStrength, @lastReadDateTime = @currentReadDateTime, @lastReaderID = @currentReaderID; 
     END 
    ELSE 
     BEGIN 
     INSERT INTO tblreaddataresults (SiteID, ReadDateTimeStart, ReadDateTimeEnd,ReadSeqStart, ReadSeqEnd, ReaderID, DirectSeconds) VALUES ('1002',@saveReadDateTime, @lastReadDateTime, @saveReadSeq, @lastReadSeq, @lastReaderID,timestampdiff(SECOND,@saveReadDateTime,@lastReadDateTime)); 
     SET @saveReadSeq = @currentReadSeq, @saveReadStrength = @currentReadStrength, @saveReadDateTime = @currentReadDateTime, @saveReaderID = @currentReaderID; 
     SET @lastReadSeq = @saveReadSeq, @lastReadStrength = @saveReadStrength,@lastReadDateTime = @saveReadDateTime, @lastReaderID = @saveReaderID; 
     END 
    SET @RowCnt = @RowCnt+1; 
END