5

我想更新名为Employeekopie1.

我要更新的列是FK_Profiel(值是 type int

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

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

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

我想分配选择查询中的所有值。

代码如下:

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;

请帮忙,谢谢。

4

4 回答 4

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
于 2011-04-20T14:33:56.080 回答
4

首先,你不需要 a CURSOR,你可以UPDATE没有它。而且您还应该使用显式JOINS而不是隐式。尝试以下操作:

UPDATE e1
SET FK_Profiel = p.ProfielID
FROM DIM_EmployeeKopie1 e1
JOIN employee e
ON e1.EmpidOrigineel = e.emplid
JOIN DIM_Profiel p
ON e.profile_code = p.Prof_Code
于 2011-04-20T14:36:17.787 回答
1
DECLARE @employee_id INT 
DECLARE @getemployee_id CURSOR 

SET @getemployee_id = CURSOR FOR 
    SELECT employee_id 
    FROM employment_History

OPEN @getemployee_id
FETCH NEXT FROM @getemployee_ID 
INTO @employee_ID 

WHILE @@FETCH_STATUS = 0 
BEGIN 
    PRINT @employee_ID 
    FETCH NEXT FROM @getemployee_ID 
    INTO @employee_id 
END 

CLOSE @getemployee_ID 
DEALLOCATE @getemployee_ID
于 2012-07-09T14:06:29.917 回答
-1
This is the simplest example of the SQL Server Cursor. I have used this all the time for any use of Cursor in my T-SQL.

DECLARE @AccountID INT
DECLARE @getAccountID CURSOR
SET @getAccountID = CURSOR FOR
SELECT Account_ID
FROM Accounts
OPEN @getAccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @AccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
END
CLOSE @getAccountID
DEALLOCATE @getAccountID
于 2012-04-13T09:19:48.737 回答