使用COUNT更新列

时间:2017-03-26 10:31:54

标签: sql-server database tsql stored-procedures

我希望参数'HoursPerWeek'等于具有特定教师ID的学生人数。 我真的迷失了如何解决这个问题。

CREATE PROC spUpdateTeachingHoursAndWages
AS
update Payments.HoursPerWeek
set HoursPerWeek = (select COUNT(PupilDetails.Teacher_ID)
FROM Assignment.dbo.Payments JOIN Assignment.dbo.PupilDetails 
ON Payments.ID = PupilDetails.Teacher_ID

3 个答案:

答案 0 :(得分:2)

如果您尝试更新HourPerWeekwith a specific Teachers ID,则应在存储过程中添加一个参数,以指示Teacher_ID。

注意:我已使用int值根据您的表架构更改它。

CREATE PROC spUpdateTeachingHoursAndWages (@Teacher_ID int)
AS
    UPDATE Payments
    SET    HoursPerWeek = (SELECT COUNT(PupilDetails.Teacher_ID)
                           FROM   Assignment.dbo.Payments 
                           JOIN   Assignment.dbo.PupilDetails 
                           ON     Payments.ID = PupilDetails.Teacher_ID
                           WHERE  Payments.ID = @Teacher_id)
    WHERE Payments.ID = @Teacher_ID

答案 1 :(得分:1)

@McNets的答案是正确的,但可以进行修改:

更好地使用table aliases并且不需要子查询:

CREATE PROC spUpdateTeachingHoursAndWages --(@Teacher_ID int)
AS
UPDATE p
SET HoursPerWeek = COUNT(pd.Teacher_ID)
FROM Assignment.dbo.Payments p
INNER JOIN Assignment.dbo.PupilDetails pd
    ON p.ID = pd.Teacher_ID
--WHERE p.ID = @Teacher_ID
--Uncomment this, if you need to change HoursPerWeek for some special teacher

答案 2 :(得分:0)

不使用特定的Teacher_ID参数:

相关子查询版本:

create proc spUpdateTeachingHoursAndWages as
begin;
set nocount, xact_abort on;
  update p 
  set HoursPerWeek = (
      select count(*)
      from Assignment.dbo.PupilDetails pd
      where pd.Teacher_id = p.id
      )
  from Assignment.dbo.Payments p;
end;
go

inner join版本:

create proc spUpdateTeachingHoursAndWages as
begin;
set nocount, xact_abort on;
  update p 
  set HoursPerWeek = pd.HoursPerWeek
  from Assignment.dbo.Payments p
    inner join (
      select 
          pd.id
        , HoursPerWeek = count(*) 
      from Assignment.dbo.PupilDetails pd
      group by pd.id
      ) pd
      on p.id = pd.Teacher_id;
end;
go

cross apply()版本:

create proc spUpdateTeachingHoursAndWages as
begin;
set nocount, xact_abort on;
  update p 
  set HoursPerWeek = pd.HoursPerWeek
  from Assignment.dbo.Payments p
    cross apply(
      select HoursPerWeek = count(*) 
      from Assignment.dbo.PupilDetails pd
      where p.id = pd.Teacher_id;
      ) pd
end;
go

注意:Why you should always include set xact_abort, nocount on; - Erland Sommarskog