Sunday, 29 September 2013

Making stored procedure after insert update other table trigger

Making stored procedure after insert update other table trigger

I've got these tables:
Reservations
Reseration_ID
User_ID
Total_Amount
Tourist_Reservation
Tourist_ID- foreign key
Reservation_ID - foreign key to Reservation
Extra_Charges table
Extra_Charge_ID
Amount
Description
Tourist_Extra_Charges
Tourist_ID - foreign key
Extra_Charge_ID - foreign key
But when a user makes a reservation at first – for example, the basic
packet costs 500 euro – it is inserted into the TotalAmount column in the
Reservation table.
But in the next form the user can select extra_charges which will (but
also he may not select any extra_charges) which are immediately inserted
in the Tourist_Extra_charges table.
The problem is that as the user has selected extra_charges I should update
the column TotalAMount.
So after insert in the tourist_extra_charges table I want to make a
trigger that will update the column TotalAmount in the Reservation table.
And this is what I came up with. Please advice me if I can optimize it and
as a whole if the procedure is good.
CREATE TRIGGER [dbo].[tralAmount] on [dbo].[TOURIST_EXTRA_CHARGES] After
Insert
AS
BEGIN
Declare @Res_ID int
Declare @Sum_toAdd money
select @Res_ID = Reservation_ID from inserted
Inner join TOURIST_RESERVATION on
inserted.Tourist_ID=TOURIST_RESERVATION.Tourist_ID
select @Sum_toAdd = Amout from inserted
Inner Join EXTRA_CHARGES on inserted.Extra_Charge_ID=
EXTRA_CHARGES.Extra_Charge_ID
Update RESERVATIONS
Set Reservation_TotalAmount = (Reservation_TotalAmount + @Sum_toAdd)
where Reservation_ID=@Res_ID
END

No comments:

Post a Comment