插入时生成标识插入错误(不在代码中)

Identity Insert error is being generated on insert (not in code)

我正在尝试使用以下代码构建 table - 创建 table 时没有错误,我可以看到 st运行 结构,它显示 IDENTITY_INSERT 设置为 ON

CREATE TABLE lt_percent_cs
(
    id_key INT IDENTITY PRIMARY KEY,   
    customer_no INT ,
    season INT,
    percentage DECIMAL,

    created_by VARCHAR(15) NULL,
    create_dt DATETIME NULL,
    last_updated_by VARCHAR(15) NULL,
    last_update_dt DATETIME NULL,
    create_loc VARCHAR(16) NULL
) ON [primary]

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].lt_percent_cs 
    ADD CONSTRAINT [lt_percent_created_by] 
        DEFAULT (user_name()) FOR [created_by]
GO

ALTER TABLE [dbo].lt_percent_cs 
    ADD CONSTRAINT [lt_percent_create_dt]  
        DEFAULT (getdate()) FOR [create_dt]
GO

ALTER TABLE [dbo].lt_percent_cs 
    ADD CONSTRAINT [lt_percent_create_loc]  
        DEFAULT [dbo].fs_location() FOR [create_loc]
GO

SET IDENTITY_INSERT lt_percent_cs ON

尝试插入数据时出现以下错误(通过应用程序而非代码)。

Last Error: Database update failed:
dataobject=

sqlca.sqlerrtext=SQLSTATE = 42000
Microsoft OLE DB Provider for SQL Server
Cannot insert explicit value for identity column in table 'lt_percent_cs' when IDENTITY_INSERT is set to OFF.

No changes made to database.

INSERT INTO lt_percent_cs (id_key, customer_no, season, percentage)
VALUES (54891, 80055514, 2017, 50)

sqlca.sqldbcode=544

sqlsyntax:
INSERT INTO lt_percent_cs (id_key, customer_no, season, percentage) VALUES (54891, 80055514, 2017, 50)

row:1 [nvo_ds_database.uf_update.34 (544)]

我应该在 运行 SQL Server Management Studio 中添加脚本,它可以正常工作,也不会生成任何错误。

INSERT INTO lt_percent_cs (id_key, customer_no, season, percentage) 
VALUES (54891, 80055514, 2017, 50)

有什么想法吗?

从 Insert 语句中删除 id_key,因为 id_key 是身份种子

INSERT INTO lt_percent_cs (customer_no, season, percentage ) VALUES ( 80055514, 2017, 50 )

否则声明id_key as integer Primary Key 然后插入应该工作

INSERT INTO lt_percent_cs ( id_key, customer_no, season, percentage ) VALUES ( 54891, 80055514, 2017, 50 )

既然你想要批量插入数据并保持身份,我可以建议将 id_key 更改为整数主键,然后批量插入,然后将字段更改回身份到 ON... 以后你不需要插入 id_key

如果你想在应用程序中插入一个明确的 Id,你必须设置 Identity_insert 并在一个事务中插入!我不知道,您使用的是哪个应用程序,但是这个规则是通用的。