UPDATE不允许在FK字段中INSERT null

时间:2016-03-18 16:39:29

标签: sql-server sql-server-2008 null sql-update foreign-keys

我有一个SQL Server数据库,在表格中有一个查找列,它是一个可以为空的FK"链接到主表。

我们在数据导入过程中将数据从table01_staging提取到table01。这是失败的UPDATE语句(如果CarrierID为空) -

DECLARE @code as nvarchar(10); SET @code = 'xyz';
UPDATE table01 
SET CarrierID = t2.CarrierID
FROM table01 AS t1 
INNER JOIN table01_staging AS t2 ON t1.Code = @code;
WHERE t1.Code = @code;

如果CarrierID不为空,那就好了。事实上我可以成功执行:

UPDATE table01 
SET CarrierID = null 
WHERE t1.Code = 'xyz';

因此设置null不是问题,但是当它从具有空值的登台表更新时它不起作用。我怎样才能做对吗?

  

错误:UPDATE语句与FOREIGN KEY约束FK_table01_MasterCarrier冲突。冲突发生在数据库table01,表dbo.MasterCarrier,列ID

>编辑02:完成!。更新了第一个SQL以显示我的变量用法 - 我认为这是罪魁祸首。使用COLLATion转换错误修复如下更正JOIN操作使其工作 -

DECLARE @code as nvarchar(10); SET @code = 'xyz';
UPDATE table01 
SET CarrierID = t2.CarrierID
FROM table01 AS t1 
INNER JOIN table01_staging AS t2 ON t1.Code = t2.code COLLATE SQL_Latin1_General_CP1_CI_AS
WHERE t1.Code = @code;

谢谢大家,特别是。张。我因为无法正确理解JOIN条款而得到-1: - )

1 个答案:

答案 0 :(得分:0)

table01_staging对CarrierID具有相同的外键约束吗?

如果没有,请检查MasterCarrier表中是否存在某些CarrierID。

select * from table01_staging t 
 where not exists (select 1 from MasterCarrier m where m.ID = t.CarrierID)

!! UPDATE !!

我创建了示例表和数据。它没有任何问题。

CREATE TABLE [dbo].MasterCarrier(
      [id] [int] IDENTITY NOT  NULL,
      [NAME] [varchar](10) NULL,
 CONSTRAINT [PK_mastertable]  PRIMARY KEY CLUSTERED 
(
      [id] ASC
)
)
GO

CREATE TABLE [dbo].[table01](
      [id] [int] NOT NULL,
      [CarrierID] [int] NULL,
      [Code] [varchar](10) NULL
) 
GO

ALTER TABLE [dbo].table01  WITH CHECK  ADD  CONSTRAINT [FK_table01_MasterCarrier] FOREIGN KEY([CarrierID])
REFERENCES [dbo].[MasterCarrier] ([id])
GO
ALTER TABLE [dbo].table01 CHECK CONSTRAINT [FK_table01_MasterCarrier]
GO

CREATE TABLE [dbo].[table01_staging](
      [id] [int] NOT NULL,
      [CarrierID] [int] NULL,
      [Code] [varchar](10) NULL
) 
GO

--Insert sample data
INSERT INTO MasterCarrier (NAME)  VALUES ('carrier');
INSERT INTO table01 (id, CarrierID, Code) VALUES (1, 1, 'abc'), (2,  NULL, 'abc'),(3, 1, 'ddd');
INSERT INTO table01_staging (id, CarrierID, Code) VALUES (1, 1, 'abc'), (2,  NULL, 'abc'),(3, 1, 'ddd');


UPDATE table01
SET CarrierID=t2.CarrierID
FROM table01 AS t1
INNER JOIN table01_staging AS t2 ON t1.ID = t2.ID
WHERE t1.Code='abc'
  

得到(2行受影响)消息。