2013-07-26 65 views
2

如何將以下過程轉換爲MySQL格式?如何將SQL Server光標轉換爲MySQL等效項

這裏是要轉換的一塊:

DECLARE @CurrentFirstName varchar(300) 
DECLARE @CurrentAge INT 

DECLARE CursorName CURSOR FAST_FORWARD FOR 
    SELECT Firstname,Age 
    FROM Customers 

OPEN CursorName 
FETCH NEXT FROM CursorName INTO @CurrentFirstName, @CurrentAge 

WHILE @@FETCH_STATUS = 0 
BEGIN 
     IF @AGE>60 /*this is stupid but we can apply any complex condition here*/ BEGIN 
    insert into ElderCustomers values (@CurrentFirstName,@CurrentAge) 
     END 


    FETCH NEXT FROM CursorName INTO @CurrentFirstname,@CurrentAge 
END 

CLOSE CursorName 
DEALLOCATE CursorName 

對不起提前如果有上述

回答

3

不對勁MySQL的等價會是這樣的:

BEGIN 
    DECLARE CurrentFirstName VARCHAR(300); 
    DECLARE CurrentAge INT; 
    DECLARE done INT DEFAULT FALSE; 
    DECLARE CursorName CURSOR FOR 
    SELECT FirstName, Age FROM Customers; 
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; 
    OPEN CursorName; 
    myloop: LOOP 
    FETCH CursorName INTO CurrentFirstName, CurrentAge; 
    IF done THEN 
     LEAVE myloop; 
    END IF; 
    IF CurrentAge > 60 THEN 
     insert into ElderCustomers values (CurrentFirstName,CurrentAge); 
    END IF; 
    END LOOP; 
    CLOSE CursorName; 
END; 

大差異在循環中,使用CONTINUE HANDLER在沒有更多行需要讀取時設置標誌,並在標誌設置時退出循環。 (這看起來很醜,但是這就是它在MySQL做的方式。)

這個例子引出這是爲什麼不寫的問題(更有效,SQL Server和MySQL的中)爲:

INSERT INTO ElderCustomers (FirstName, Age) 
SELECT FirstName, Age 
    FROM Customers 
WHERE Age > 60