Based on your examples, I have also tried:
- Drop and recreate the foreign key.
- Drop and recreate the table.
Then I noticed something in the command:
NOT FOR REPLICATION
It seems if a constraint is created with NOT FOR REPLICATION, it is always not trusted.
Quoting from Books Online:
In some cases, it is desirable for user activity in a replication
topology to be treated differently from agent activity. For example,
if a row is inserted by a user at the Publisher and that insert
satisfies a check constraint on the table, it might not be required to
enforce the same constraint when the row is inserted by a replication
agent at the Subscriber. The NOT FOR REPLICATION option allows you to
specify that the following database objects are treated differently
when a replication agent performs an operation:
Foreign key constraints
The foreign key constraint is not enforced when a replication agent
performs an insert, update, or delete operation.
It looks like the IS_NOT_TRUSTED
setting is only relevant for replication influenced by IS_NOT_FOR_REPLICATION
. I guess as long as the constraint is enforced on the server you are working on, it should be fine. So I went ahead and confirmed it:
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
INSERT INTO dbo.Sale VALUES (2, GETDATE(), 1.00)
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Product_ProductKeyId". The conflict occurred in database "_Scratch", table "dbo.Product", column 'ProductKeyId'.
The statement has been terminated.
If you still want to see IS_NOT_TRUSTED = 0
for peace of mind, just recreate the foreign key without NOT FOR REPLICATION
.
In case if those of you are wondering, I have verified the same effect on CHECK constraints as well.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…