主键具有不同值的外键关系

时间:2014-12-18 15:35:55

标签: sql sql-server tsql ssis

我想在表中创建外键关系,但我想要给予关系的列有一个额外的字符。例如,如果在主键中,如果它是另一个表中的PPL(Foreignkey),则它是PPL.M.有人可以告诉我如何才能给出这两列之间的关系。如何避免额外的角色。

此致 KK

2 个答案:

答案 0 :(得分:3)

您可以将计算列添加到引用的表中以修剪其他聊天

alter table tablea
add coly as (substring(colx,1,5)) persisted

然后引用此列

alter table tableb
create constraint fk_tableb_colx 
foreign key (colx)
references tablea(coly)

或者你可以使用触发器

create trigger trg_tableb_fk_colx
on tableb
for insert, update
as
begin
    if exists(select 1 from inserted
              where inserted.colx not in(select substring(colx, 1, 5) from tablea))
    begin
        raiserror('violation of foreign key trg_tableb_fk_colx',16,1)
    end
end

答案 1 :(得分:0)

您可能需要使用 NOCHECK 选项创建Foreign Key

ALTER TABLE dbo.child_table
    WITH NOCHECK
    ADD CONSTRAINT FK_childtable FOREIGN KEY (child_col) REFERENCES 
    dbo.Parent_table(Parent_col)