使用SQL Server 2008 R2中的游标进行更新

use*_*316 5 sql sql-server cursor sql-server-2008

我想更新一个名为的特定表中的列Employeekopie1.

我想要更新的列是FK_Profiel(值是类型int)

我试图在列FK_Profiel中放置的值是我从游标中获取的值.游标从不同表中的列获取值,使用连接获取正确的值.

使用的选择查询的结果返回具有不同值的多个行.

select查询的第一个结果是114,这是正确的.问题是这个值被分配给列中的所有字段FK_Profiel,这不是我的意图.

我想从select查询中分配所有值.

代码如下:

DECLARE @l_profiel int;
DECLARE c1 CURSOR  
FOR select p.ProfielID 
from DIM_Profiel p,DIM_EmployeeKopie1 e1,employee e
where e1.EmpidOrigineel = e.emplid and e.profile_code = p.Prof_Code
for update of e1.FK_Profiel;
open c1;
FETCH NEXT FROM c1 into @l_profiel
WHILE @@FETCH_STATUS = 0
BEGIN
SET NOCOUNT ON;
        UPDATE DIM_EmployeeKopie1
        set FK_Profiel = @l_profiel
        where current of c1

end

close c1;
deallocate c1;
Run Code Online (Sandbox Code Playgroud)

请帮助,thx.

Qua*_*noi 11

你忘了加入FETCH NEXT循环.

但是根本不需要光标.

试试这个:

UPDATE  e1
SET     FK_Profiel = p.ProfielID
FROM    DIM_EmployeeKopie1 e1
JOIN    employee e
ON      e.emplid = e1.EmpidOrigineel
JOIN    DIM_Profiel p
ON      p.Prof_Code = e.profile_code
Run Code Online (Sandbox Code Playgroud)