为什么SCOPE_IDENTITY()在一个表上插入后返回NULL而不在另一个表上?

时间:2016-07-13 13:14:12

标签: sql-server tsql identity scope-identity

为什么SCOPE_IDENTITY()ComponentAssociation表中插入行后返回NULL(因为@@IDENTITY返回正确的Id) 虽然SCOPE_IDENTITY()CustomerProjectAssociation表中插入行后返回正确的ID?

两个关联表以相同的方式创建。

以下是表创建脚本的摘录:

-- Creating table 'CustomerProjectAssociation'
CREATE TABLE [dbo].[CustomerProjectAssociation] 
(
    [Id] int IDENTITY(1,1) NOT NULL,
    [CustomerId] int  NOT NULL,
    [ProjectId] int  NOT NULL,
    [CreationDate] datetime NOT NULL CONSTRAINT DF_CustomerProjectAssociation_CreationDate DEFAULT (SYSUTCDATETIME()),
    [LastModificationDate] datetime NOT NULL CONSTRAINT DF_CustomerProjectAssociation_ModificationDate DEFAULT (SYSUTCDATETIME())
);
GO

-- Creating table 'ComponentAssociation'
CREATE TABLE [dbo].[ComponentAssociation] 
(
    [Id] int IDENTITY(1,1) NOT NULL,
    [EcuId] int  NOT NULL,
    [CreationDate] datetime NOT NULL CONSTRAINT DF_ComponentAssociation_CreationDate DEFAULT (SYSUTCDATETIME()),
    [LastModificationDate] datetime NOT NULL CONSTRAINT DF_ComponentAssociation_ModificationDate DEFAULT (SYSUTCDATETIME()),
    [ComponentId] int  NOT NULL
);
GO

-- Creating primary key on [Id] in table 'CustomerProjectAssociation'
ALTER TABLE [dbo].[CustomerProjectAssociation]
      ADD CONSTRAINT [PK_CustomerProjectAssociation]
          PRIMARY KEY CLUSTERED ([Id] ASC);
GO

-- Creating primary key on [Id] in table 'ComponentAssociation'
ALTER TABLE [dbo].[ComponentAssociation]
      ADD CONSTRAINT [PK_ComponentAssociation]
          PRIMARY KEY CLUSTERED ([Id] ASC);
GO

以下是从SQL Server Management Studio对数据库执行的两个查询:

INSERT [dbo].[CustomerProjectAssociation]([CustomerId], [ProjectId])
VALUES (1, 2)

SELECT 
    [RowCount] = @@RowCount,
    [@@IDENTITY] = @@IDENTITY,
    [SCOPE_IDENTITY] = SCOPE_IDENTITY()

结果:

    RowCount @@IDENTITY SCOPE_IDENTITY
        1         24          24

INSERT [dbo].[ComponentAssociation]([EcuId], [ComponentId])
VALUES(1, 2)

SELECT 
    [RowCount] = @@RowCount,
    [@@IDENTITY] = @@IDENTITY,
    [SCOPE_IDENTITY] = SCOPE_IDENTITY()

结果:

    RowCount @@IDENTITY SCOPE_IDENTITY
        1        613        NULL

1 个答案:

答案 0 :(得分:0)

好的,这个问题已经解决了。

在此处找到解决方案:error when inserting into table having instead of trigger from entity data framework

我在而不是insert,update触发器的末尾添加了以下select语句,返回所有计算列:

select [Id], [CreationDate], [LastModificationDate] from {0}.[dbo].[ComponentAssociation] where @@ROWCOUNT > 0 and Id = scope_identity()