Sql server 2008 相关表的sql srvr 2008插入触发器?

Sql server 2008 相关表的sql srvr 2008插入触发器?,sql-server-2008,Sql Server 2008,我有以下模式: [dbo].[tbl_事件] [Event_ID] [uniqueidentifier] NOT NULL (PK) [Location_ID] [uniqueidentifier] NULL (FK) [Observation] [nvarchar] [dbo]。[tbl_位置] [Event_ID] [uniqueidentifier] NOT NULL [Location_ID] [uniqueidentifier] NULL (PK) [Notes] [nvarchar

我有以下模式:

[dbo].[tbl_事件]

[Event_ID] [uniqueidentifier] NOT NULL (PK)
[Location_ID] [uniqueidentifier] NULL (FK)
[Observation] [nvarchar]
[dbo]。[tbl_位置]

[Event_ID] [uniqueidentifier] NOT NULL
[Location_ID] [uniqueidentifier] NULL (PK)
[Notes] [nvarchar]
Locations是通过Location ID与事件建立关系的父表

位置_ID在位置中创建时设置为NewID(),事件_ID在事件中创建时设置为NewID()。由于管理复制的组织策略,表、关系和PK格式不可更改


我正在寻找有关如何定义插入触发器的建议,该触发器将在事件中创建新行,并从父位置表中提取位置id和新的唯一事件id。例如,当(外部应用程序无法嵌入sql代码)创建新位置记录时,它获取的位置id为8170daed-92c8-47f1-98ca-147800329686,触发器还会创建一个新的事件记录,其位置ID为8170daed-92c8-47f1-98ca-147800329686,事件ID为cfed8fe8-b5be-4f78-b366-008672E3967。

我将假设您的dbo.tbl\u位置模式定义只是输入错误,而位置ID在事件ID为NULL时不为NULL(因为位置_ID是主键并自动生成)

您将在tbl_位置上创建一个插入后触发器,该触发器将新记录插入tbl_事件,然后检索该事件ID以更新tbl_位置表

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

我将假设您的dbo.tbl_Locations模式定义只是输入错误,并且Location_ID不为NULL,而Event_ID为NULL(因为Location_ID是PK并自动生成的)

您将在tbl_位置上创建一个插入后触发器,该触发器将新记录插入tbl_事件,然后检索该事件ID以更新tbl_位置表

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