为什么SCOPE_IDENTITY()在表中插入一行后返回NULL ComponentAssociation(@@IDENTITY返回正确的Id),而SCOPE_IDENTITY()在表中插入一行后返回正确的Id CustomerProjectAssociation?
两个关联表的创建方式相同。
这是表创建脚本的摘录:
-- 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