2016-10-01 121 views
0

我查詢更新表HumanResources.EmployeePayHistory所有記錄,而不是隻有那些更新,其中患病小時< = 20 ...SQL服務器更新查詢不能

而且我意識到某些領域正在更新超過1次。

我不一定非要使用下面的這種格式,但我必須使用while命令來完成這項工作(需求)。

我正在使用AdventureWorks2012數據庫。

DECLARE SickHours CURSOR FOR 
select distinct e.BusinessEntityID, p.FirstName, p.LastName, e.JobTitle, e.SickLeaveHours, 
round(eph.Rate, 2) as NewHourlyRate 
from Person.Person p 
inner join HumanResources.Employee e 
on p.BusinessEntityID = e.BusinessEntityID 
inner join HumanResources.EmployeePayHistory eph 
on e.BusinessEntityID = eph.BusinessEntityID 
where e.SickLeaveHours <= 20; 
OPEN SickHours; 
FETCH NEXT FROM SickHours; 
WHILE @@FETCH_STATUS = 0 
    BEGIN 
     update HumanResources.EmployeePayHistory 
     set Rate = (Rate * 1.1), ModifiedDate = GETDATE()  
     FETCH NEXT FROM SickHours; 
    END; 
CLOSE SickHours; 
DEALLOCATE SickHours; 
GO 

我該如何解決?

感謝

回答

1

我注意到,你的更新語句缺乏WHERE條款。我認爲,這就是爲什麼你要更新所有的記錄,而不是那些病歷< = 20的記錄。另外,當你正在提取記錄時,你不會將這些值初始化爲變量,你完全應該這樣做,否則使用遊標是絕對無用功

既然你說你需要使用遊標,請嘗試以下查詢:

--DECLARE VARIABLES TO STORE CURSOR DATA INTO 
DECLARE @BusinessEntityID VARCHAR(250) 
DECLARE @FirstName VARCHAR(250) 
DECLARE @LastName VARCHAR(250) 
DECLARE @JobTitle VARCHAR(250) 
DECLARE @SickLeaveHours INT --CHANGE TYPE AS NEEDED 


DECLARE SickHours CURSOR FOR 
select distinct e.BusinessEntityID, p.FirstName, p.LastName, e.JobTitle, e.SickLeaveHours, 
round(eph.Rate, 2) as NewHourlyRate 
from Person.Person p 
inner join HumanResources.Employee e 
on p.BusinessEntityID = e.BusinessEntityID 
inner join HumanResources.EmployeePayHistory eph 
on e.BusinessEntityID = eph.BusinessEntityID 
where e.SickLeaveHours <= 20; 
OPEN SickHours; 
FETCH NEXT FROM SickHours INTO @BusinessEntityID, @FirstName, @LastName, @JobTitle, @SickLeaveHours; 
WHILE @@FETCH_STATUS = 0 
    BEGIN 
     update HumanResources.EmployeePayHistory 
     set Rate = (Rate * 1.1), ModifiedDate = GETDATE() 
     where HumanResources.EmployeePayHistory.BusinessEntityID = @BusinessEntityID --WHERE STATEMENT TO UPDATE THE PROPER ROWS 

     FETCH NEXT FROM SickHours INTO @BusinessEntityID, @FirstName, @LastName, @JobTitle, @SickLeaveHours; 
    END; 
CLOSE SickHours; 
DEALLOCATE SickHours; 
GO