无法在表中插入标识列的显式值

时间:2017-05-17 10:03:33

标签: c# sql asp.net sql-server database

代码:

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[AddUpdateCustomer]
      @CustomerID NCHAR(5),
      @ContactName NVARCHAR(30),
      @CompanyName NVARCHAR(40)
AS
BEGIN
      SET NOCOUNT ON;
    IF EXISTS(SELECT * FROM Customers WHERE CustomerID = @CustomerID)
    BEGIN
            UPDATE [Customers]
            SET [CompanyName] = @CompanyName
               ,[ContactName] = @ContactName
            WHERE CustomerID = @CustomerID
    END
    ELSE
    BEGIN
            INSERT INTO [Customers]
           ([CustomerID]
           ,[CompanyName]
           ,[ContactName])
        VALUES
           (@CustomerID
           ,@CompanyName
           ,@ContactName)
    END

    SELECT [CustomerID]
          ,[CompanyName]
          ,[ContactName]
      FROM Customers         
END

当我在文本框中插入数据时,会发生以下错误:

  

无法在表格中插入标识列的显式值'客户'当IDENTITY_INSERT设置为OFF时

2 个答案:

答案 0 :(得分:4)

ALTER PROCEDURE [dbo].[AddUpdateCustomer]
      @CustomerID  INT           OUTPUT,
      @ContactName NVARCHAR(30),
      @CompanyName NVARCHAR(40)
AS
BEGIN
      SET NOCOUNT ON;
    IF EXISTS(SELECT * FROM Customers WHERE CustomerID = @CustomerID)
    BEGIN
            UPDATE [Customers]
            SET [CompanyName] = @CompanyName
               ,[ContactName] = @ContactName
            WHERE CustomerID = @CustomerID
    END
    ELSE
    BEGIN
        INSERT INTO [Customers]
           ([CompanyName]
           ,[ContactName])
        VALUES
           (@CompanyName
           ,@ContactName)
        SET @CustomerID = SCOPE_IDENTITY()
    END

    SELECT [CustomerID]
          ,[CompanyName]
          ,[ContactName]
    FROM Customers  
    WHERE [CustomerID] = @CustomerID
END

答案 1 :(得分:0)

对于标识列,您无法显式插入数据。要明确地将数据插入标识列,您需要将IDENTITY_INSERT设置为ON。您可以使用下面的方法来执行此操作。

 SET IDENTITY_INSERT Database.table_name ON