sql srvr 2008 insert trigger for related table?
I have the following schema:
[dbo].[tbl_Events]
[Event_ID] [uniqueidentifier] NOT NULL (PK)
[Location_ID] [uniqueidentifier] NULL (FK)
[Observation] [nvarchar]
[dbo].[tbl_Locations]
[Event_ID] [uniqueidentifier] NOT NULL
[Location_ID] [uniqueidentifier] NULL (PK)
[Notes] [nvarchar]
Locations is the parent table with a relationship to events through Location ID.
Location_ID is set to b开发者_JAVA百科e NewID() on create in Locations, and Event_ID is set to be NewID() on create in events. The table, relationship, and PK format is non-changeable due to organizational policy governing replication.
I'm looking for advice on how to define an insert trigger that will create a new row in events, with the location_id pulled from the parent location table, and a new unique event_id. E.g., when (by outside application with no ability to embed sql code) a new location record is created, it gets a location_id of 8170daed-92c8-47f1-98ca-147800329686, and the trigger creates a new event record also with a location_ID of 8170daed-92c8-47f1-98ca-147800329686 and an event_ID of cfed8fe8-b5be-4f78-b366-008672e39637.
I'm going to assume that your dbo.tbl_Locations schema definition is just typo'd and Location_ID is NOT NULL while Event_ID is NULL (since Location_ID is the PK and auto-generated).
You'll create an after insert trigger on tbl_Locations that inserts the new records into tbl_Events and then retrieves that Event_ID to update the tbl_Locations table.
create trigger trLocationsInsert on dbo.tbl_Locations after insert as
insert into dbo.tbl_Events (Location_ID) select Location_ID from inserted
update l
set Event_ID = e.Event_ID
from inserted i
inner join dbo.tbl_Locations l on i.Location_ID = l.Location_ID
inner join dbo.tbl_Events e on l.Location_ID = e.Location_ID
精彩评论