Update with select not working as expected

时间:2016-07-11 20:42:31

标签: sql sql-server-2008

I have two tables

First Table

create table ApprovedLeave(
Username varchar(100),
FromDate date,
ToDate date,
type varchar(100),
address varchar(1000),
contactNo varchar(20),
NoofWorkingDays int,
);

Second Table

create table EMPLOYEE(
FName varchar(100),
LName varchar(200),
Username varchar(100),
NoOfDaysRemaining int,
constraint emp1 primary key(Username)); 

Once the leave is approved, I want to update with this logic:

NoOfDaysRemaining = NoOfDaysRemaining- NoofWorkingDays

So far what I have doesn't perform the above operation.

   create Procedure UpdateNoOfDays2 
   AS
BEGIN  
update le
    set NoOfDaysRemaining = al.sum_NoofWorkingDays
    from EMPLOYEE le join
         (select UserName, sum(NoofWorkingDays) as sum_NoofWorkingDays
          from ApprovedLeave
          group by UserName
         ) al
         on le.UserName = al.UserName
         End

How can I add in this logic?

1 个答案:

答案 0 :(得分:2)

Your question is missing a question, but based on this:

NoOfDaysRemaining = NoOfDaysRemaining- NoofWorkingDays

Are you wanting this? SET NoOfDaysRemaining = NoOfDaysRemaining - al.sum_NoofWorkingDays

UPDATE le
SET    NoOfDaysRemaining = NoOfDaysRemaining - al.sum_NoofWorkingDays
FROM   EMPLOYEE le 
INNER JOIN
         (SELECT   UserName, sum(NoofWorkingDays) as sum_NoofWorkingDays
          FROM     ApprovedLeave
          GROUP BY UserName
         ) al ON le.UserName = al.UserName