2017-03-26 79 views
0

我希望參數'HoursPerWeek'等於具有特定教師ID的學生人數。 我真的失去了如何去做這件事。使用COUNT的更新列

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 

回答

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

謝謝你,但我得到一個'無效的對象name'錯誤HoursPerWeek。將嘗試查看造成衝突的原因。 –

+0

對不起,我以爲付款是模式名稱,但它的表名稱,刪除.HoursPerWeek – McNets

+0

感謝您的答覆,我其實已經想通了:)感謝您的幫助! –

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