如何使用单个存储过程一次更新两个表?

时间:2012-03-01 06:55:12

标签: sql-server-2008 c#-4.0

我的数据库RequestsBalance跟踪器中有两个表没有关系....但我想从两个表中选择数据并将其绑定到两个网格...

请求

EmpID | EmpRqsts | EmpDescription | ApproverID | ApprovedAmount | RequestPriority
   1  | asdfsb   | sadbfsbdf      |     1      |
   2  | asbfd    | sjkfbsd        |     1      |

余额跟踪器

EmpId | BalanceAmnt | LastUpdated | lastApprovedAmount
  1   |    5000     | sdfbk       |
  2   |    3000     | sjbfsh      |

现在我想根据EmpID一次更新两个表。只要金额获得批准,就应该在request表格列[ApprovedAmount]中进行更新,并优先考虑......

更新[ApprovedAmount]时[BalanceAmnt]也应通过添加已批准的金额来更新余额跟踪器,[LastUpdated],[lastApprovedAmount]应更新日期和时间

请有人帮我查询....

2 个答案:

答案 0 :(得分:0)

首先创建一个存储过程来更新[ApprovedAmount]

create procedure SP_UpdateRequestedAmount
    (@EmpID int,
     @AmountApproved varchar (50),
     @RequestPriority varchar (50))
as
begin
    Update Requests   
    set ApprovedAmount = @AmountApproved,
        Request_Priority = @RequestPriority 
    where
        Emp_ID = @EmpID
end

然后在更新[AmountApproved]列时使用triger更新另一个表

CREATE TRIGGER tr_ApprovedAmount_UPDATE 
ON Requests   
AFTER UPDATE 
AS 
    --Make sure Priority was changed 
    IF NOT UPDATE(ApprovedAmount) 
        RETURN 

    --Determine if Priority was changed to high 

    -- PUT your queries for Updatating other table 
     declare @Balance_LastUpdated date
     declare @ApprovedDate date

     UPDATE Balance Tracker
     SET Balance Tracker.Balance_BalanceAmount =  Balance Tracker.Balance_BalanceAmount +   PTS_Requests.Request_IsApproved,
         Balance_LastUpdated = @Balance_LastUpdated,
         Balance_LastApproval = @ApprovedDate
     FROM
         Balance Tracker 
     INNER JOIN
         Requests ON Balance Tracker.Emp_ID = Requests.Emp_ID

希望这有助于.........

答案 1 :(得分:0)

请尝试使用out trigger

    CREATE procedure SP_UpdateRequestedAmount
   (
   @EmpID int,
   @AmountApproved varchar (50),
   @RequestPriority varchar (50)
   )
   as
   begin

   --Declare a variable for know current ApprovedAmount (that is before updation)
   Declare @CurrentApprovedAmount AS INT

   --set current ApprovedAmount
   SET @AmountApproved =(SELECT ApprovedAmount FROM Requests WHERE EmpID=@EmpID)

   --check is @CurrentApprovedAmount differ from @AmountApproved
   IF (@CurrentApprovedAmount!=@AmountApproved)
        BEGIN
                --Here we need to update  Requests and BalanceTracker
        END
    ELSE
        BEGIN
            --only update Requests -- no change in AmountApproved
        END 

   go