如何解决级联插入上的空 Scope_Indentity?

How to resolve a null Scope_Indentity on cascaded insert?

我正在 SQL 服务器存储过程中执行级联插入。然后我将 SCOPE_IDENTITY 从第一个 table 插入的 ID 传递到第二个 table.

但是在执行存储过程期间,我得到了 SCOPE_IDENTITY:

的 NULL 值

Msg 515, Level 16, State 2, Procedure InsertDDM_UserProfile, Line 43
Cannot insert the value NULL into column 'Filter', table '.....dbo.DDM_Dashboard'; column does not allow nulls. INSERT fails.

问题:为什么存储过程return使用SCOPE_IDENTITY的空ID?

这是我起草的存储过程。已为 table 设置 FK 约束:

ALTER PROCEDURE [dbo].[InsertDDM_UserProfile]
   @p_email VARCHAR(100),
   @p_dashboardName VARCHAR(100),
AS 
BEGIN    
    INSERT INTO [dbo].[DDM_User] ([Email])
    VALUES (@p_email)

    INSERT INTO [dbo].[DDM_Dashboard] ([Dashboard_Name], [DDM_USER_ID])
    VALUES (@p_dashboardName, SCOPE_IDENTITY())
END

下面是两个table的结构:

DDM_User-

CREATE TABLE [dbo].[DDM_User]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Email] [varchar](80) NOT NULL,

    CONSTRAINT [PK_DDMUser] 
        PRIMARY KEY CLUSTERED ([ID] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                          ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

DDM_Dashboard:

CREATE TABLE [dbo].[DDM_Dashboard]
(
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Dashboard_Name] [varchar](100) NOT NULL,
    [DDM_USER_ID] [int] NOT NULL,

    CONSTRAINT [PK_DDMDashboard] 
        PRIMARY KEY CLUSTERED ([ID] ASC)
                    WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                          IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                          ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[DDM_Dashboard] WITH NOCHECK 
    ADD CONSTRAINT [FK_DDMDashboard_DDMUser] 
        FOREIGN KEY([DDM_USER_ID]) REFERENCES [dbo].[DDM_User] ([ID])
GO

ALTER TABLE [dbo].[DDM_Dashboard] CHECK CONSTRAINT [FK_DDMDashboard_DDMUser]
GO

这与 SCOPE_IDENTITY() 无关,在您第二次插入时:

INSERT INTO [dbo].[DDM_Dashboard] ([Dashboard_Name], [DDM_USER_ID])
VALUES (@p_dashboardName, SCOPE_IDENTITY())

您只插入两列 [Dashboard_Name][DDM_USER_ID]。您没有为列 [Filter] 指定值,根据您的错误消息,该值不允许空值,因此您的插入失败。

DECLARE @Value1 varchar(50) = 'Test1', @Value2 varchar(50) = 'Test2';

DECLARE @Table1 table (Id int NOT NULL IDENTITY(1,1), Value varchar(50) NOT NULL);
DECLARE @Table2 table (Id int NOT NULL, Value varchar(50) NOT NULL);

INSERT INTO @Table1 (Value1)
OUTPUT inserted.Id, @Value2 INTO @Table2 (Id, Value)
Values (@Value1)
;

SELECT * FROM @Table1;
SELECT * FROM @Table1;

编辑: 正如 GarethD 指出的那样,由于外键约束,这实际上不是解决问题的有效方法。但是在其他情况下,这是处理级联插入和更新的有用方法,因为它是两个记录的原子操作。