空FK引用导致FK约束错误

时间:2017-01-30 14:08:50

标签: sql sql-server

在部署中,我不得不回滚,因为SQL导致了FOREIGN KEY CONSTRAINT错误。该表有数百万行。任何人都可以在这个SQL中看到任何会导致这种情况的内容吗?

我不再像以前那样有原始信息了:

  

FOREIGN KEY约束“FSomeTable1”

......它真的非常香草

其他信息:

  • 这是一个新栏目
  • SEED DATA将在另一个脚本中执行,因此tResult_Status中没有数据

表定义:

CREATE TABLE [dbo].[SomeTable](
    [Claim_ID] [varchar](25) NOT NULL,
    ...other columns do exist...
    [Result_Status_Id] [uniqueidentifier] NULL,
PRIMARY KEY CLUSTERED 
(
    [Claim_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [stp].[tResult_Status](
    [Result_Status_Id] [UNIQUEIDENTIFIER] NOT NULL CONSTRAINT [DResult_Status]  DEFAULT (NEWSEQUENTIALID()),
    [Result_Status_Name] [NVARCHAR](50) NOT NULL,
    [System_Value_Indicator] [BIT] NOT NULL,
    [Executed_By_Name] [NVARCHAR](400) NOT NULL,
    [Executed_Datetime] [DATETIME] NOT NULL,
 CONSTRAINT [PResult_Status] PRIMARY KEY CLUSTERED 
(
    [Result_Status_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]

部署文章声明:

ALTER TABLE [dbo].[SomeTable]  WITH CHECK ADD  CONSTRAINT [FSomeTable1] FOREIGN KEY([Result_Status_Id])
REFERENCES [dbo].[tResult_Status] ([Result_Status_Id])
GO

ALTER TABLE [dbo].[SomeTable] CHECK CONSTRAINT [FSomeTable1]
GO

1 个答案:

答案 0 :(得分:2)

因为你在SomeTable中有一个在tResult_Status中没有对应值的值,所以不能创建FK约束。您可以使用此类查询(基于您的表名称)查找哪些记录没有有效值。

SELECT * 
FROM SomeTable s 
WHERE NOT EXISTS (SELECT 1 FROM tResult_Status r WHERE r.Result_Status_Id = s.Result_Status_Id)