编写存储过程时为什么会出现错误8101?

时间:2018-11-24 08:01:09

标签: sql-server tsql

我有一个名为Sales的表

CREATE TABLE Sales
(
    SaleID int IDENTITY(1,1) PRIMARY KEY 
    ,DateOfTransaction dateTime  NOT NULL
    ,QuantitySold int NOT NULL
    ,PaymentMethod nvarchar(40) NOT NULL
    ,EquipmentID int FOREIGN KEY  REFERENCES Equipments(EquipmentID)
    ,CustomerID int  FOREIGN KEY REFERENCES Customers(CustomerID)
    ,SalespersonID int FOREIGN KEY REFERENCES Salespersons(SalespersonID)
);

我正在编写一个要在其中插入数据的存储过程。到目前为止,这是我的代码:

CREATE PROCEDURE dbo.sproc_PurchaseAdd
    @SaleID INT OUTPUT 
    ,@DateOfTransaction dateTime
    ,@QuantitySold int
    ,@PaymentMethod nvarchar(40)
    ,@EquipmentId int
    ,@CustomerID int
    ,@SalesPersonId int
AS 
BEGIN
    SET IDENTITY_INSERT Sales ON

    INSERT INTO Sales 
    VALUES (@DateOfTransaction, @QuantitySold, @PaymentMethod, @EquipmentId, @CustomerID, @SalesPersonId)

    SET @SaleID = @@IDENTITY 
END
GO

但是我遇到一个错误:

  

消息8101,级别16,状态1,过程sproc_PurchaseAdd,第13行[批处理开始第75行]
  仅当使用列列表且IDENTITY_INSERT为ON时,才能为表“ Sales”中的Identity列指定一个显式值。

有什么我想念的东西吗?请帮帮我

1 个答案:

答案 0 :(得分:0)

SaleID为IDENTITY,因此它将自动递增

您不需要这个:

SET IDENTITY_INSERT Sales ON

没关系:

INSERT INTO Sales VALUES (@DateOfTransaction,@QuantitySold,@PaymentMethod,@EquipmentId,@CustomerID,@SalesPersonId)

如果这不起作用,请尝试指定列:

INSERT INTO Sales (DateOfTransaction,QuantitySold,PaymentMethod,EquipmentID,CustomerID,SalespersonID) VALUES (@DateOfTransaction,@QuantitySold,@PaymentMethod,@EquipmentId,@CustomerID,@SalesPersonId)

也尝试使用SCOPE_IDENTITY()代替@@ IDENTITY