1 sql database sql-server relation
多年前,我们在 MS SQL 中创建了许多没有表关系的表。现在我们正在尝试在这些表之间创建关系。问题在于这些开发人员中的许多人在表中使用了假 ID。
例如:TABLE A, ID(primary key) -> TABLE B, AID 需要是关系型的。但是开发人员使用了一些像 -1,-2 这样的假 id 来解决他们身边的一些问题。现在,当我尝试在 TABLE A, ID(primary key) -> TABLE B, AID 之间创建关系时,出现错误。
表A
ID | NAME
1 | name01
2 | name02
Run Code Online (Sandbox Code Playgroud)
表B
ID | NAME | AID
1 | name01 | 1
2 | name02 | -1
3 | name03 | -2
Run Code Online (Sandbox Code Playgroud)
有没有办法解决这个问题,这是否意味着开发人员所做的一切,他们没有在 sql 中使用任何关系,他们在代码隐藏中控制一切。
谢谢
您需要将它们添加到您的参考表中。像这样的东西:
insert into a (id, name)
select distinct aid, 'Automatically Generated'
from b
where not exists (select 1 from a where b.aid = a.id) and
a.id is not null;
Run Code Online (Sandbox Code Playgroud)
然后就可以添加外键关系了:
alter table b add constraint fk_b_aid foreign key (aid) references a(id);
Run Code Online (Sandbox Code Playgroud)