sql server - Why does this T-SQL OUTPUT INTO with FOREIGN KEY hack work? -


the base example lifted no way use tsql output normal foreign key constraints?; code fails expected. if way constraint defined in example modified below, defining fk constraint with nocheck , checking it, output run unimpeded.

this seems contradict output clause docs. specifically:

output_table [the table receiving into] cannot:

•have enabled triggers defined on it.

participate on either side of foreign key constraint [emphasis added].

•have check constraints or enabled rules.

from relational perspective below could work, action supposed precluded. if fk defined straight "with check" (the default) fails expected. if defined "with nocheck" , enabled "check constraint" it, well, fails fail.

it awesome if known, supported feature. or did find bug in sql that's persisted since @ least sql 2008 (i tested 2008 , 2014)? why work? why shouldn't it? risking using it?

if object_id ('dbo.forn') not null begin     alter table dbo.forn drop constraint fk_forn_prim     drop table dbo.forn; end if object_id ('dbo.prim') not null     drop table dbo.prim; go  create table dbo.prim (c1 int primary key); create table dbo.forn (c1 int ); alter table dbo.forn nocheck add constraint fk_forn_prim foreign key (c1) references dbo.prim(c1); alter table dbo.forn check constraint fk_forn_prim ; go  -- in fact fail foreign key constraint violation insert dbo.forn values (2);  -- works!! insert dbo.prim     output inserted.c1 dbo.forn select 1; 

the foreign key still not trusted system after check statement. because default existing constraints nocheck, you're running:

    alter table dbo.forn nocheck check constraint fk_forn_prim; 

correct statement re-enable is:

    alter table dbo.forn check check constraint fk_forn_prim; 

the nested insert fail again after running that. not recommended leave fk untrusted sql not consider many operations.

you can check untrusted fk's in system view sys.foreign_keys, is_not_trusted field.

more here: http://sqlblog.com/blogs/hugo_kornelis/archive/2007/03/29/can-you-trust-your-constraints.aspx


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

Augmenting Latin Hypercube Points in MATLAB -