我有两张表,销售和产品。Sale 有一个引用 Product 的外键约束。外键已创建WITH NOCHECK
并在创建后立即禁用。我想启用并信任外键约束。启用它可以工作,但我无法信任它。
StackOverflow 和各种博客上的类似问题表明运行ALTER TABLE T WITH CHECK CHECK CONSTRAINT C
应该导致is_disabled=0
and is_not_trusted=0
,但is_not_trusted
对我来说始终是 1。我究竟做错了什么?
我试图将示例代码放在 SQL Fiddle 上,但它不喜欢“DBCC”命令,所以这里是:
-- "_Scratch" is just a sandbox DB that I use for testing stuff.
USE _Scratch
CREATE TABLE dbo.Product
(
ProductKeyId INT PRIMARY KEY NOT NULL,
Description VARCHAR(40) NOT NULL
)
CREATE TABLE dbo.Sale
(
ProductKeyId INT NOT NULL,
SaleTime DATETIME NOT NULL,
Value MONEY NOT NULL
)
ALTER TABLE dbo.Sale WITH NOCHECK
ADD CONSTRAINT FK_Product_ProductKeyId FOREIGN KEY (ProductKeyId)
REFERENCES dbo.Product (ProductKeyId) NOT FOR REPLICATION;
ALTER TABLE dbo.Sale NOCHECK CONSTRAINT FK_Product_ProductKeyId
INSERT INTO dbo.Product VALUES (1, 'Food')
INSERT INTO dbo.Sale VALUES (1, GETDATE(), 1.00)
-- Check the disabled/trusted state
SELECT name, is_disabled, is_not_trusted
FROM sys.foreign_keys
WHERE name = 'FK_Product_ProductKeyId'
-- name is_disabled is_not_trusted
-- FK_Product_ProductKeyId 1 1
-- Check the FK_Product_ProductKeyId constraint
DBCC CHECKCONSTRAINTS('FK_Product_ProductKeyId')
-- DBCC execution completed.
-- If DBCC printed error messages, contact your system administrator.
-- Check all constraints on Sale table
DBCC CHECKCONSTRAINTS('Sale')
-- DBCC execution completed.
-- If DBCC printed error messages, contact your system administrator.
-- Add the constraint and check existing data
ALTER TABLE Sale WITH CHECK CHECK CONSTRAINT FK_Product_ProductKeyId
-- Check the disabled/trusted state
SELECT name, is_disabled, is_not_trusted
FROM sys.foreign_keys
WHERE name = 'FK_Product_ProductKeyId'
-- name is_disabled is_not_trusted
-- FK_Product_ProductKeyId 0 1
-- Check the FK_Product_ProductKeyId constraint
DBCC CHECKCONSTRAINTS('FK_Product_ProductKeyId')
-- DBCC execution completed.
-- If DBCC printed error messages, contact your system administrator.
-- Check all constraints on Sale table
DBCC CHECKCONSTRAINTS('Sale')
-- DBCC execution completed.
-- If DBCC printed error messages, contact your system administrator.