FOR INSERT触发器不触发

时间:2013-08-26 06:16:22

标签: sql sql-server tsql triggers sql-server-2008-r2

我遇到插入触发器问题

这是我的触发码:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create TRIGGER [dbo].[Vtriggers] ON [dbo].[stats]
FOR INSERT
AS
INSERT INTO [NewDB].dbo.NewStat (StatID)
SELECT ID
FROM inserted

奇怪的是,我构建了另一个表,就像我想在其中触发的表一样,触发器适用于新的表,但在旧表上它不起作用。 info:在旧表中我同时有多个插入。

这是我的两张表的架构:

旧的统计数据(触发不起作用)

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[stats](
    [ID] [int] IDENTITY(1,1) NOT NULL,
      [Code] [nvarchar](100) NULL,
 CONSTRAINT [PK_Stat] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  =    ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

和新的测试统计(触发器可以使用它):

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Teststats](
    [ID] [int] IDENTITY(1,1) NOT NULL,
      [Code] [nvarchar](100) NULL,
 CONSTRAINT [PK_Teststats] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  =    ON, ALLOW_PAGE_LOCKS  = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

这是我在另一个db上的目标表:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[NewStat](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [StatID] [int] NULL,
) ON [PRIMARY]

GO

触发器在创建触发器用户后不再插入旧的统计信息表,但是在具有相同模式的测试表上,触发器工作得很好!

2 个答案:

答案 0 :(得分:0)

你有错误的插入语句因此它不执行触发器。 正确的如下。

CREATE TRIGGER [dbo].[Vtriggers] ON [dbo].[stats]
FOR INSERT
AS
INSERT  INTO [NewDB].dbo.NewStat
        ( StatID )
VALUES  ( ID )

答案 1 :(得分:-1)

试试这个: -

create TRIGGER [dbo].[Vtriggers] ON [dbo].[stats]
FOR INSERT
AS
INSERT INTO [NewDB].dbo.NewStat (StatID) values(SELECT max(ID)
FROM inserted)