2011-04-20 27 views
5

Bir imleç ile güncelleştirmek Employeekopie1 adlı belirli bir tabloda bir sütunu güncelleştirmek istiyorum.SQL Server 2008 R2

Güncelleme için çalışıyorum sütundur FK_Profiel

ben sütunda FK_Profiel koymak için çalışıyorum değerler bir imleç alıyorum değerlerdir (değerler tip int vardır). İmleç, doğru değerleri elde etmek için birleştirmeler kullanarak farklı bir tablodaki bir sütundan değerler alıyor.

Kullanılan sorgu sorgusunun sonucu, farklı değerler içeren birden çok satır döndürür.

Seçim sorgusunun ilk sonucu, doğru olan 114'dür. Sorun, bu değerin, niyetim olan FK_Profiel sütunundaki tüm alanlara atanmasıdır.

Seçme sorgusundaki tüm değerleri atamak istiyorum.

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; 

yardım edin, thx şu şekildedir:

kodudur.

cevap

11

Döngünün içine FETCH NEXT eklemeyi unutmuşsunuzdur. Bunun için bir imleçe ihtiyacınız yoktur.

bu deneyin:

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 
+0

Eh, buna beni yendi. +1. – Lamak

+0

Cevaplar için teşekkürler. Bu benim problemimi çözdü. – user717316

+0

zarafet hareket halinde, +1 – Paceman

4

İlk af hepsi, bunun için bir CURSOR gerekmez, onsuz bir UPDATE yapabilirsiniz. Ayrıca, örtük olanlar yerine açık JOINS kullanmalısınız. Aşağıdaki deneyin:

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 
+0

+1. Bunun için imlecin kullanılması sunucunun yavaş olmasını ve set yönelimli bir düşünme eksikliğini ortaya çıkarmasını istiyor. – TomTom

-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 
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