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()?