在这个例子中,来自不同员工的薪水和奖金混合在while循环中,这使得计算无效。
如何独立迭代每个ID并根据该ID进行某些计算?
while (select count(*) from db.employee) > 0
begin
select top 1 ID, SALARY, [month]
from db.employee
order by [month] asc
if deserve = yes
begin
set SALARY = SALARY + (bonus * 2)
end
end
这不是我的剧本。我有复杂的脚本,需要时间来理解目标。但是,我模仿这个简单想法的逻辑。所以稍后我可以根据建议调整我的原始脚本。原始的是Iterate through tables and do calculation based on one column SQL server
答案 0 :(得分:0)
你可以通过多种方式做到这一点。
首先,我只是好奇你为什么不进行正常的更新?
update emp
set salary = emp.salary + (bonus * 2)
from employee emp
join bonuses bon on bon.employee_id = emp.employee_id
where bon.deserved = 1
另一种方法是使用CURSOR,但由于性能问题,人们不太喜欢它们:https://docs.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql
另一种方法是创建一个容器来保存员工数量,然后循环通过,而当前的itteration不等于计数并在每个循环中获取所需的员工,例如
declare @employeecount int = (select count(*) from employee)
declare @current int = 1
while @current <= @employeecount
begin
declare @employeeid uniqueidentifier = (select top 1 employee_id from (select top (@current) * from employee order by employee_id asc) tmp order by employee_id desc)
-- Grab Employee and run logic
set @current = @current + 1;
end
底部差不多就是CURSORS所做的,但我注意到游标做得更好。
以下是我最近采取的行动。我发现它更容易跟随。
declare @ids table (id uniqueidentifier)
insert into @ids
select employee_id
from employee
while (select count(*) from @ids) > 0
begin
declare @employeeid uniqueidentifier = (select top 1 employee_id from @ids)
-- Grab Employee and run logic
delete from @ids where id = @employeeid
end