1

插入触发器有问题

这是我的触发代码:

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

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

这是我的两个表的架构:

旧的统计信息(触发器不起作用)

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]

这是我在另一个数据库上的目标表:

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

触发器在具有相同架构的测试表上运行良好,但在创建触发器后用户无法再插入旧表后,在旧统计表中!

4

2 回答 2

0

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

CREATE TRIGGER [dbo].[Vtriggers] ON [dbo].[stats]
FOR INSERT
AS
INSERT  INTO [NewDB].dbo.NewStat
        ( StatID )
VALUES  ( ID )
于 2013-08-26T06:27:32.837 回答
-1

尝试这个 :-

create TRIGGER [dbo].[Vtriggers] ON [dbo].[stats]
FOR INSERT
AS
INSERT INTO [NewDB].dbo.NewStat (StatID) values(SELECT max(ID)
FROM inserted)
于 2013-08-26T07:22:46.213 回答