SQL技巧:唯一性约束
以下是演示唯一性约束作为外键引用点的示例代码:
create table parent
(parent_id int not null, -- Primary key
parent_alternate_key int not null, -- Alternate key
parent_col1 int null,
parent_col2 int null,
constraint pk_parent_id primary key (parent_id),
constraint ak_parent_alternate_key unique_
(parent_id, parent_alternate_key)
)
go
insert parent values ( 1, 10, 150, 151)
insert parent values ( 2, 11, 122, 271)
insert parent values ( 3, 12, 192, 513)
insert parent values ( 4, 13, 112, 892)
go
create table child2
(child2_parent_id int not null, -- Primary key/Foreign key
child2_id int not null, -- Primary key
child2_col1 int null,
child2_parent_alternate_key int not null, -- Foreign key
constraint pk_child2 primary key (child2_parent_id, child2_id),
constraint fk_child2_parent foreign key (child2_parent_id)
references dbo.parent(parent_id),
constraint fk_pk_ak_child2_parent foreign key _
(child2_parent_id, child2_parent_alternate_key) _
references dbo.parent(parent_id, parent_alternate_key)
)
go
insert child2 values (1,1,34,10)
insert child2 values (4,2,34,13)
insert child2 values (2,3,34,11)
go
insert child2 values (1,4,34,23) -- This one will fail
go