日期:2014-05-18  浏览次数:20533 次

游标的重复执行
表tableA:
----------------------------
  id name isFlag
  001 张三 0 
  002 李四 0 
  003 王五  
  004 赵六  
  005 陈七 1  
----------------------------
  我现在要取出tableA的isFlag,如果isFlag是1,执行一个update的操作;如果不为1,则执行另一个update的操作。
  下面是我用游标做的,为什么在else的里面,会重复执行多次?
-----------------------------
  DECLARE @isFlag char(1)  
  DECLARE CursorIsFlag CURSOR FOR
SELECT IsFlag FROM tableA FOR READ ONLY  
OPEN CursorIsFlag
FETCH NEXT FROM CursorIsFlag INTO @isFlag
WHILE @@FETCH_STATUS = 0  
BEGIN  
FETCH NEXT FROM CursorIsFlag INTO @isFlag  
IF @isFlag ='1'  
BEGIN  
UPDATE tableB
SET B.id='002'  
FROM tableA A LEFT JOIN tableB B  
ON A.id = B.id  
END  
ELSE  
UPDATE tabelC
SET B.id='003'  
FROM tableA A LEFT JOIN tabelC B  
ON A.id = B.id

FETCH NEXT FROM CursorIsFlag INTO @isFlag

END

CLOSE CursorIsFlag
DEALLOCATE CursorIsFlag
 
  Go
-----------------------------






------解决方案--------------------
先改成这个样子再看逻辑:
SQL code
DECLARE @isFlag char(1)   
DECLARE CursorIsFlag CURSOR FOR    SELECT IsFlag FROM tableA FOR READ ONLY   
OPEN CursorIsFlag 
FETCH NEXT FROM CursorIsFlag INTO @isFlag
WHILE @@FETCH_STATUS = 0   
BEGIN       
    IF @isFlag ='1'   
    BEGIN   
        UPDATE tableB    SET B.id='002' FROM tableA A LEFT JOIN tableB B   ON A.id = B.id   
    END   
    ELSE   
    UPDATE tabelC    SET B.id='003' FROM tableA A LEFT JOIN tabelC B   ON A.id = B.id 
FETCH NEXT FROM CursorIsFlag INTO @isFlag
END

CLOSE CursorIsFlag
DEALLOCATE CursorIsFlag

------解决方案--------------------
SQL code

    DECLARE @isFlag char(1)   
    DECLARE CursorIsFlag CURSOR FOR 
    SELECT IsFlag FROM tableA FOR READ ONLY   
    OPEN CursorIsFlag 
    FETCH NEXT FROM CursorIsFlag INTO @isFlag
    WHILE @@FETCH_STATUS = 0   
    BEGIN    
        IF @isFlag ='1'   
        BEGIN   
            UPDATE b 
            SET B.id='002'   
            FROM tableA A LEFT JOIN tableB B   
            ON A.id = B.id   
        END   
        ELSE
        begin   
            UPDATE b 
            SET B.id='003'   
            FROM tableA A LEFT JOIN tabelC B   
            ON A.id = B.id 
        end
        FETCH NEXT FROM CursorIsFlag INTO @isFlag

    END
    CLOSE CursorIsFlag
    DEALLOCATE CursorIsFlag
        --你的游标里,每次更新的是所有能匹配上的数据,
        --最终的结果是根据游标获取[color=#FF0000]最后的一条信息决定是 002 还是 003[/color]
        --多次执行 是因为你的update语句原因