2

Today I found some foreign key constraints in one of our SQL Server datbases which were not trusted using the following statement:

SELECT name, is_not_trusted
FROM   sys.foreign_keys
WHERE is_not_trusted = 1

I tried to fix the problem quickly using the following syntax and thought that the second check will ensure the FK is trusted again.

ALTER TABLE dbo.<TableName>
  WITH CHECK CHECK CONSTRAINT <FK_NAME>

The statement completed successfully but the FK is still reported as "Not trusted". I did not find any reason therefore? Does anyone have an idea?

I already have a workaround. Dropping and Recreating the FK fixes the problem but I still wonder why the ALTER command did have no effect

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
Tobi DM
  • 23
  • 4

1 Answers1

1

My guess is that you have constraint created with NOT FOR REPLICATION:

CREATE TABLE val(id INT PRIMARY KEY, name VARCHAR(100));

CREATE TABLE tab(id INT IDENTITY(1,1) PRIMARY KEY, 
                 val_id INT);
GO

ALTER TABLE tab WITH NOCHECK 
ADD CONSTRAINT fk_val FOREIGN KEY (val_id) REFERENCES val(Id) NOT FOR REPLICATION;

ALTER TABLE tab NOCHECK CONSTRAINT fk_val;
GO


-- Insert Data
INSERT INTO tab(val_id)
VALUES (10),(20);
GO

INSERT INTO val(id)
VALUES(10),(20);

-- check data
ALTER TABLE tab WITH CHECK CHECK CONSTRAINT fk_val;

-- check is_trusted
SELECT name, is_not_trusted, is_not_for_replication
FROM   sys.foreign_keys
WHERE is_not_trusted = 1;

LiveDemo

Output:

╔═══╦════════╦════════════════╦════════════════════════╗
║   ║  name  ║ is_not_trusted ║ is_not_for_replication ║
╠═══╬════════╬════════════════╬════════════════════════╣
║ 1 ║ fk_val ║ True           ║ True                   ║
╚═══╩════════╩════════════════╩════════════════════════╝
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275