我正在编写代码,使用T-SQL中的AdventureWorks2012将数据插入到现有表中。我希望代码自动生成新插入行的ID。我的代码编写如下。该消息表明代码已成功完成。但是,当调用该过程时,我收到错误消息
消息515,级别16,状态2,过程insertprocEPH,第13行
无法将值NULL插入列' BusinessEntityID',表' AdventureWorks2012.HumanResources.EmployeePayHistory&#39 ;;列不允许空值。 INSERT失败。该语句已被终止。
这是我的代码。请告诉我代码有什么问题。谢谢大家
IF OBJECT_ID(N'HumanResources.insertprocEPH', N'P') IS NOT NULL
DROP PROCEDURE HumanResources.insertprocEPH
GO
CREATE PROCEDURE HumanResources.insertprocEPH
(
@RateChangeDate DATETIME ,
@Rate MONEY ,
@PayFrequency TINYINT = 2 ,
@BusinessEntityID INT OUTPUT
)
AS
SET NOCOUNT ON
BEGIN
INSERT INTO HumanResources.EmployeePayHistory(RateChangeDate, Rate, PayFrequency)
VALUES(@RateChangeDate, @Rate, @PayFrequency);
SET @BusinessEntityID = SCOPE_IDENTITY();
END;
GO
DECLARE @NewBEntityID INT;
EXEC HumanResources.insertprocEPH
@RateChangeDate = '2012-05-25',
@Rate = 4,
@BusinessEntityID = @NewBEntityID OUTPUT
GO
答案 0 :(得分:0)
HumanResource.EmployePayHistory.BusinessEntityID
列没有IDENTITY
属性:
Column_name Type Computed Length Prec Scale Nullable
---------------- --------- -------- ----------- ----- ----- --------
BusinessEntityID int no 4 10 0 no
RateChangeDate datetime no 8 no
Rate money no 8 19 4 no
PayFrequency tinyint no 1 3 0 no
ModifiedDate datetime no 8 no
Identity Seed Increment Not For Replication
--------------------------- ---- --------- -------------------
No identity column defined. NULL NULL NULL
此外,HumanResource.EmployeePayHistory.BusinessEntityID
是指向HumanResources.Employee.BusinessEntityID
主键的外键。
这意味着您应该在HumanResource.EmployeePayHistory.BusinessEntityID
(FK)中插入HumanResources.Employee.BusinessEntityID
(PK)中已存在的值。