根据条件更新表中的所有行

时间:2014-05-18 07:02:31

标签: sql sql-server tsql if-statement while-loop

我有一个名为Training的表,其中包含Employee ID,Hours,is3ManDay等行。在此表中,可能有多个记录对应于同一个Employee。

我必须计算与每个员工ID相关的小时数,我这样做了

SELECT EMP_ID, SUM(HRS) AS TOTALHRS, is3ManDay
from Training
GROUP BY EMP_ID, is3ManDay

工作完全没问题,但现在我想根据每个员工的总小时数将is3ManDay更新为是或否

@Emp_ID int,
@is3ManDay varchar(10)
IF (SELECT SUM(Hrs) FROM Training WHERE Emp_ID = @Emp_ID) >= 36
BEGIN
   UPDATE Training
   SET is3ManDay = 'Y'
   Where Emp_ID = @Emp_ID
END
ELSE
   UPDATE Training
   SET is3ManDay = 'N'
   Where Emp_ID = @Emp_ID

这个也很好但是我必须手动更改@Emp_ID并执行不实用的存储过程。我想在这段代码中包含一个循环,但如果我删除@Emp_ID,它将更新所有具有相同值的行,因为没有选择ID。

WHILE (SELECT SUM(HRS) FROM Training) >= 36
BEGIN
   UPDATE Training
   SET is3ManDay = 'Y'
END

我尝试了WHILE声明,但没有为我工作。

2 个答案:

答案 0 :(得分:5)

你不需要是程序性的。使用SQL:

UPDATE Training
SET is3ManDay = 'Y'
Where Emp_ID in 
(SELECT Emp_ID FROM Training HAVING SUM(Hrs) >= 36)

答案 1 :(得分:0)

merge into Training x
using (
    select emp_id, case when sum_hrs >= 36
                        then 'Y' else 'N' 
                   end as is3ManDay
    from (
        select emp_id, sum(hrs) as sum_hrs
        from training
        group by emp_id
    )
) y
    on x.emp_id = y.emp_id
when matched then
    update set is3ManDay = y.is3ManDay