如何在级联插入上解析null Scope_Indentity?

时间:2016-11-09 16:21:27

标签: sql-server tsql foreign-keys scope-identity

我正在SQL Server存储过程中执行级联插入。然后我将SCOPE_IDENTITY从第一个表插入的ID传递给第二个表。

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

的NULL值
  

Msg 515,Level 16,State 2,Procedure InsertDDM_UserProfile,Line 43
  无法将值NULL插入列'Filter',表'..... dbo.DDM_Dashboard';列不允许空值。 INSERT失败。

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

这是我草拟的存储过程。已经为表格设置了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

下面是两个表的结构:

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

2 个答案:

答案 0 :(得分:2)

在第二次插入期间,这与SCOPE_IDENTITY()无关:

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

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

答案 1 :(得分:1)

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指出的那样,由于外键约束,这实际上并不是解决问题的有效方法。但是在其他情况下,这是处理级联插入和更新的有用方法,因为它是两个记录的原子操作。