I have the tables Cities and Countries with the following triggers:
When I update any City, it should insert a row into the Audit table saying 'The City with ID 'any ID' has been modified'. Cities table has a foreign key relationship with Countries table (Cities.CountryID = Countries.ID).
What I expect trCountryUpdate to do is, when I update a Country row, it should insert row into the Audit table for all the Cities having the updated Country ID.
However, when I update the name of Country with ID 1, it should have inserted 5 rows into the Audit table as there are 5 corresponding Cities for CountryID 1. However, it always inserts 1 row.
Please let me know what should be done to insert 5 rows into Audit table for 5 cities having CountryID 1 when Country with ID 1 is updated.
PS:
ALTER trigger [dbo].[trCityUpdate]
on [dbo].[Cities]
for update
as
declare @cityIdModified int;
select @cityIdModified = ID from inserted;
Insert into Audit values ('The City with ID ' + cast(@cityIdModified as varchar(1)) + ' has been modified')
go
ALTER trigger [dbo].[trCountryUpdate]
on [dbo].[Countries]
for update
as
declare @countryIdModified int;
select @countryIdModified = ID from inserted;
update ci
set ci.CountryID = @countryIdModified
from Cities ci
join Countries co on co.ID = ci.CountryID
where ci.CountryID = @countryIdModified
Thank you for all your replies. It was a great help :)
When 5 rows in Cities table are updated, trCityUpdate is called only once, not 5 times. The inserted table contains 5 updated rows.