我正在SQL Server存储过程中执行级联插入。然后,我将SCOPE_IDENTITY
从第一个表插入的 ID 传递到第二个表。
但是在执行存储过程期间,我得到了SCOPE_IDENTITY
的 NULL 值:
Msg 515,级别 16,状态 2,过程 InsertDDM_UserProfile,第 43
行 无法将值 NULL 插入到"筛选器"列、表".....德博。DDM_Dashboard';列不允许空值。插入失败。
问:为什么存储过程使用 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
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指出的那样,由于外键约束,这实际上并不是解决问题的有效方法。但是,在其他情况下,这是处理级联插入和更新的有用方法,因为它是两个记录的原子操作。