1

我有一张桌子让我们说TableA。我创建了一个trigger在插入、更新或删除记录时触发的函数,TableA并在另一个表中插入记录让我们说TableB。现在我在哪里发现困难来自我正在返回stored procedures的一些。当我从. 有没有办法解决这个问题?我只想从,从。等待您的宝贵回复。TableAscope_identity()inserted recordTableA'sTableBscope_identity()TableANOTTableB

提前致谢..

4

1 回答 1

1

SCOPE_IDENTITY() 应该在这种情况下工作,它的作用域应该是您的存储过程和对 TableA 的插入,而不是在触发器中完成的插入。

CREATE TABLE [dbo].[TableA](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [TestColumn] [nvarchar](50) NULL
) ON [PRIMARY]

CREATE TABLE [dbo].[TableB](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [TestColumn] [nvarchar](50) NULL
) ON [PRIMARY]

CREATE TRIGGER [dbo].[TableA_AIDU]
   ON  [dbo].[TableA]
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
    SET NOCOUNT ON;
    INSERT INTO TableB ( TestColumn )
    SELECT 'TableA Modified'
END

CREATE PROCEDURE [dbo].[sp_InsertToTableA]
    @ID INT OUTPUT  
AS
BEGIN
    SET NOCOUNT ON;
    INSERT TableA ( TestColumn )
    SELECT 'Insert from sp_InsertToTableA'
    SET @ID = SCOPE_IDENTITY()
END

The stored proc returns the ID from TableA, and the TableB insert is triggered as expected. Are you sure you're not using @@IDENTITY instead of SCOPE_IDENTITY()?

于 2013-01-18T06:00:00.787 回答