自动插入识别存储过程的关键

时间:2015-02-18 22:21:56

标签: sql sql-server sql-server-2008 stored-procedures

我正在编写代码,使用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   

1 个答案:

答案 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

enter image description here

此外,HumanResource.EmployeePayHistory.BusinessEntityID是指向HumanResources.Employee.BusinessEntityID主键的外键。

这意味着您应该在HumanResource.EmployeePayHistory.BusinessEntityID(FK)中插入HumanResources.Employee.BusinessEntityID(PK)中已存在的值。

请参阅referential integrity

相关问题