我的问题
我可以在同一个表上有2个Insert,Update触发器并让它们都工作。
我有3个表都具有完全相同的架构TestTable, TestTable2, TestTable3
为方便起见,Schema如下所示我在触发器代码下有create-schema命令:
PK - int(这是主键) 名字 - vcharchar(10) TheValue - int
他们尝试将TestTable中插入和更新的行与TestTable2和TestTable3同步
如果我禁用1触发,则其他工作,反之亦然。
我的问题>这两个触发器都可以在表上运行吗
下面定义了2个触发器和模式:
USE [WQMetaData]
GO
/****** Object: Trigger [dbo].[TESTTABLETRIGGER] Script Date: 05/03/2018 10:59:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE TRIGGER [dbo].[TESTTABLETRIGGER]
ON [dbo].[testtable]
AFTER INSERT, update
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @thevalue int,@pk int, @existingPK int
set @existingPK = 0
select @thevalue= thevalue from inserted
select @pk = pk from inserted
select @existingPK = pk from WQMetaData.dbo.TESTTABLE2 where pk = @pk
if @existingPK <= 0
begin
Insert into WQMetaData.dbo.TESTTABLE2 (pk,name, thevalue)
select
inserted.pk,
inserted.name,
inserted.thevalue
from inserted
end
if @pk > 0
begin
update WQMetaData.dbo.TESTTABLE2 set thevalue = @thevalue where pk = @pk
end
END
GO
**2nd trigger**
USE [WQMetaData]
GO
/****** Object: Trigger [dbo].[TESTTABLETRIGGER2] Script Date: 05/03/2018 11:00:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE TRIGGER [dbo].[TESTTABLETRIGGER2]
ON [dbo].[testtable]
AFTER INSERT, update
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @thevalue int,@pk int, @existingPK int
set @existingPK = 0
select @thevalue= thevalue from inserted
select @pk = pk from inserted
select @existingPK = pk from WQMetaData.dbo.TESTTABLE2 where pk = @pk
if @existingPK <= 0
begin
Insert into WQMetaData.dbo.TESTTABLE3 (pk,name, thevalue)
select
inserted.pk,
inserted.name,
inserted.thevalue
from inserted
end
if @pk > 0
begin
update WQMetaData.dbo.TESTTABLE3 set thevalue = @thevalue where pk = @pk
end
END
GO
USE [WQMetaData]
GO
/****** Object: Table [dbo].[testtable] Script Date: 05/03/2018 11:33:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[testtable](
[PK] [int] NOT NULL,
[NAME] [varchar](12) NOT NULL,
[TheValue] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO