引用约束已触发,但无法从表中选择会触发引用约束的行

时间:2019-05-21 21:01:53

标签: sql sql-server

我正在尝试更新数据库中的许多不同表。 但是,更新完成后,由于外键约束,我无法从另一个表中删除记录。但是,不同服务器上的其他数据库将接受更改。在创建一个新的新数据库并对其应用一系列更新脚本以预填充数据后,它也会失败。

应该是SQL Server 2016。

我有一个同事尝试重建索引并更新用法,但仍然失败。

--- Query 1
SELECT  ROW_NUMBER() OVER(ORDER BY c.[name], t.[name]),
        SCHEMA_NAME(t.schema_id) AS SchemaName,
        c.[name] AS ColName, 
        t.[name] AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE   c.[name] IN (...)
AND     t.[name] NOT IN (...)
ORDER BY ColName, TableName

我选择了符合我的条件的架构,列和表的集合,并为每种组合生成动态SQL。

--- Query 2
SET @sql = 'UPDATE ' + @schemaName + '.' + @tableName + ' SET ' + @colName + ' = ' + CONVERT(NVARCHAR, @p1) + ' WHERE ' + @colName + ' = ' + CONVERT(NVARCHAR, @p2)

查询1返回的大多数/所有表都具有针对另一个表的FK约束。 而且查询2似乎可以正确执行而没有问题。

表定义如下:

CREATE TABLE [Table1](
    [Table1ID] [int] NOT NULL,
    [ColX] [int] NOT NULL,
    [ColY] [int] NOT NULL,
    ...
    [ColZ] [int] NOT NULL,
    ...
) ON [PRIMARY]

ALTER TABLE [Table1] ADD  CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED 
(
    [Table1ID] ASC,
    [ColY] ASC,
    [ColZ] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

ALTER TABLE [Table1]  WITH CHECK ADD  CONSTRAINT [FK_Table1_ColY_Table2_ColY] FOREIGN KEY([ColY])
REFERENCES [Table2] ([ColY])

CREATE TABLE [Table2](
    [Table2ID] [int] IDENTITY(1,1) NOT NULL,
    [ColY] [int] NOT NULL,
    [ColZ] [int] NOT NULL,
    ...
) ON [PRIMARY]

ALTER TABLE [Table2] ADD  CONSTRAINT [PK_Table2] PRIMARY KEY CLUSTERED 
(
    [Table2ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

ALTER TABLE [Table2] ADD  CONSTRAINT [UK_Table2_ColY] UNIQUE NONCLUSTERED 
(
    [ColY] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

我的期望是,当我运行以下命令时:

DELETE  FROM Table2
WHERE   ColY = @p2

我不触发FK_Table1_ColY_Table2_ColY。

特别是因为:

SELECT   *
FROM     Table1
WHERE    ColY = @p2

不返回任何记录。

完整的错误消息如下:

Msg 547, Level 16, State 0
The DELETE statement conflicted with the REFERENCE constraint 
"FK_Table1_ColY_Table2_ColY". The conflict occurred in database "localhost", table 
"dbo.Table1", column 'ColY'.

1 个答案:

答案 0 :(得分:0)

似乎在sql服务器更新中已解决了一个问题。

Support Microsoft: Fix referential integrity constraints not being evaluated correctly.

详细的解决方法是:

  1. 使用低于130的兼容级别。

  2. 修改引用表以更改索引结构。