无法通过“身份列”

时间:2018-07-23 15:31:28

标签: sql sql-server

我有此过程:

create proc insertfactors_pf
(
    @FactorID int,
    @CustomersID int,
    @Number int,
    @TotalPrice decimal(18, 0),
    @PaidPrice decimal(18, 0),
    @Date Date,
    @ProductID int,
    @QTY int

)
AS

BEGIN TRANSACTION

SET IDENTITY_INSERT facetors on


INSERT INTO Factor VALUES (@FactorID, @CustomersID, @Number, @TotalPrice, @PaidPrice,@Date)
SET IDENTITY_INSERT factors off

IF @@ERROR <> 0
BEGIN 
    ROLLBACK
    RETURN
END

SET IDENTITY_INSERT Product_Factor on
INSERT INTO Produc_Factor values(@FactorID,@ProductID,@QTY)
SET IDENTITY_INSERT Product_Factor off


IF @@ERROR <> 0
BEGIN
    ROLLBACK
    RETURN
END

COMMIT

但是当我运行它时,出现此错误:

  

消息8101,级别16,状态1,过程insertfactors_pf,第20行[批处理开始第0行]
  只有在使用列列表且IDENTITY_INSERT为ON的情况下,才能为表'Factor'中的identity列指定一个显式值。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

错误消息似乎很清楚:FactorId是一个标识列。 您不应该自己设置FactorID的值。 Sql Server会为您设置它。但是,如果出于某些疯狂的原因确实要设置它,则需要在查询中包括一个列列表,如下所示:

SET IDENTITY_INSERT facetors on
    INSERT INTO Factor 
        (FactorID, CustomerID, Number, TotalPrice, PaidPrice, Date)
    VALUES 
        (@FactorID, @CustomersID, @Number, @TotalPrice, @PaidPrice,@Date)
SET IDENTITY_INSERT factors off

更好的是,您应该做更多类似的事情,而不必担心身份插入问题:

create proc insertfactors_pf
(
    @CustomersID int,
    @Number int,
    @TotalPrice decimal(18, 0),
    @PaidPrice decimal(18, 0),
    @Date Date,
    @ProductID int,
    @QTY int
)
AS

--Move this to inside the procedure definition. Don't ask for it as an argument
DECLARE @FactorID int

BEGIN TRANSACTION

--Don't mention FactorID anywhere here. Sql Server will take care of it
INSERT INTO Factor
    (CustomersID, Number, TotalPrice, PaidPrice, Date)
VALUES 
    (@CustomersID, @Number, @TotalPrice, @PaidPrice,@Date);

IF @@ERROR <> 0
BEGIN 
    ROLLBACK
    RETURN
END

--use scope_idenity() to get the FactorID value Sql Server just created
SELECT @FactorID = scope_identity();

INSERT INTO Produc_Factor 
    (FactorID, ProductID, Qty)
VALUES 
    (@FactorID,@ProductID,@QTY)

IF @@ERROR <> 0
BEGIN
    ROLLBACK
    RETURN
END

COMMIT