即使条目已存在,插入时也会出现FOREIGN KEY约束错误

Bis*_*hop 0 sql sql-server sql-server-2008

我创建了两个表,Customers和Records.记录对customerID有外键约束.当我尝试将记录插入已存在的客户时,它会给我这个错误:

  Message (The INSERT statement conflicted with the FOREIGN KEY constraint "FK_REC_cstmr_int_id". The conflict occurred in database "Omitted", table "dbo.CST_NEW_CUSTOMER", column 'cstmr_int_id'.)
Run Code Online (Sandbox Code Playgroud)

这是插入代码:

INSERT INTO [Omitted].[dbo].[REC_NEW_RECORDS]
       ([cstmr_int_id]
       ,[xml_tx]
VALUES
       (10
       ,'<test>test</test>'
GO
Run Code Online (Sandbox Code Playgroud)

我在这里找到的大多数相关问题都谈到了插入错误的顺序,但我可以选择id为10的客户.任何指针都将受到赞赏.

编辑1:这将返回一个客户

SELECT [cstmr_int_id]
   FROM [Omitted].[dbo].[CST_NEW_CUSTOMER] WHERE cstmr_int_id =10
Run Code Online (Sandbox Code Playgroud)

编辑2:这是记录表的创建脚本

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[REC_NEW_RECORDS](
[rec_int_id] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[cstmr_int_id] [int] NOT NULL,
[xml_tx] [varchar](max) NULL,
CONSTRAINT [REC_PK_rec_int_id] PRIMARY KEY CLUSTERED 
(
[rec_int_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[REC_NEW_RECORDS]  WITH CHECK ADD  CONSTRAINT [FK_REC_cstmr_int_id] FOREIGN KEY([cstmr_int_id])
REFERENCES [dbo].[CST_NEW_CUSTOMER] ([cstmr_int_id])
GO
Run Code Online (Sandbox Code Playgroud)

Ker*_*mit 5

引用的表中不存在该值.这是10您引用的表中没有的场景:

建立

create table cst_new_customer (
  cstmr_int_id int not null primary key);

insert into cst_new_customer (cstmr_int_id) values (9), (11);

create table rec_new_records (
  cstmr_int_id int not null primary key,
  xml_tx varchar(50));

alter table rec_new_records add constraint fk_rec_cstmr_int_id
foreign key (cstmr_int_id) references cst_new_customer (cstmr_int_id);
Run Code Online (Sandbox Code Playgroud)

测试1

insert into rec_new_records values (10, 'test');
Run Code Online (Sandbox Code Playgroud)

结果

INSERT语句与FOREIGN KEY约束"fk_rec_cstmr_int_id"冲突.冲突发生在数据库"db_3_055da",表"dbo.cst_new_customer",列'cstmr_int_id':

测试2

insert into rec_new_records values (11, 'test');
Run Code Online (Sandbox Code Playgroud)

结果

| CSTMR_INT_ID | XML_TX |
|--------------|--------|
|           11 |   test |

看演示