嵌套游标不循环遍历所有项目

时间:2014-04-15 20:57:04

标签: sql sql-server sql-server-2008 tsql

    DECLARE @Webusers table 
(
    webusersid varchar(08),
    namefml varchar(100)
)

INSERT INTO @Webusers (webusersid, namefml)
SELECT MAX(wb.webusersid), c.namefml
from webusers wb 
inner join contact c on c.contactid=wb.contactid
where c.contactrecordtype='CONTACT'
group by c.namefml
order by c.namefml


-- Store duplicate contact Webusersid that is not in WebUsers table
DECLARE @TempWebusers table 
(
    webusersid varchar (08),
    namefml varchar (100)
)

INSERT INTO @TempWebusers (webusersid, namefml)
Select wb.webusersid, c.namefml 
from webusers wb
inner join contact c on c.contactid=wb.contactid
WHERE 
c.contactrecordtype='CONTACT'
 and wb.webusersid NOT IN (Select webusersid from @Webusers);

 --SELECT * from @TempWebusers

--- create cursor 

Declare @currentWebusersid varchar(08)
Declare @currentnamefml varchar(100)

--Declare @innerWebusersid varchar(08)
Declare @innerorderid varchar(100)

Declare cursor_webusers cursor for 
Select webusersid, namefml from @TempWebusers

Open cursor_webusers
fetch NEXT from cursor_webusers into @currentWebUsersid, @currentnamefml 


/*select orderid
        from dealorder do
        where orderid<>'' 
        and webusersid<>''
        and webusersid IN (select webusersid from @TempWebusers) */


While @@FETCH_STATUS = 0
BEGIN
   -- declare all the dealid and webusersid that will need to be modified 
    DECLARE Cur2 CURSOR FOR 
        select orderid
        from dealorder do
        where orderid<>'' 
        and webusersid<>''
        and webusersid IN (select webusersid from @TempWebusers)
    OPEN Cur2
    FETCH NEXT FROM Cur2 INTO @innerorderid

    WHILE @@FETCH_STATUS=0
    BEGIN 
        --- update dealorder webusersid to the MAX   
        PRINT 'UPDATING '+ @currentnamefml+' '+@currentWebusersid + ' in '+@innerorderid

        UPDATE do
        SET webusersid= wb.webusersid
         from dealorder do, @Webusers wb  
        where wb.webusersid=@currentWebusersid
        and orderid=@innerorderid 
        and wb.namefml LIKE @currentnamefml

        FETCH NEXT FROM Cur2 INTO @innerorderid

    fetch NEXT from cursor_webusers into @currentWebUsersid, @currentnamefml 
    END
    CLOSE Cur2
    DEALLOCATE Cur2 
END 

    /*DELETE webusers 
    FROM webusers wb 
    where webusersid IN (Select webusersid from @TempWebusers) */

这似乎只是通过前10个订单ID迭代而不是遍历所有迭代。这个嵌套游标做错了吗?有些东西是关闭的,不是很安静。因此,delete语句不起作用,因为webusers表中仍然存在webusersid。请帮忙。

1 个答案:

答案 0 :(得分:0)

END位置错误。还修复了嵌套游标的释放。

    FETCH NEXT FROM Cur2 INTO @innerorderid

fetch NEXT from cursor_webusers into @currentWebUsersid, @currentnamefml 
END
CLOSE Cur2
DEALLOCATE Cur2 

必须是

    FETCH NEXT FROM Cur2 INTO @innerorderid
END
CLOSE Cur2
DEALLOCATE Cur2 

fetch NEXT from cursor_webusers into @currentWebUsersid, @currentnamefml