SQL Table 关系

SQL Table Relations

我们在 MS SQL 中有很多 table 是多年前在没有 table 关系的情况下创建的。现在我们正在尝试在这些 table 之间建立关系。问题在于许多开发人员在 tables.

中使用了假 ID

例如: TABLE A, ID(主键) -> TABLE B, AID需要是关系型的。但是开发人员使用了一些伪造的 ID,例如 -1、-2 来解决他们身边的一些问题。现在,当我尝试在 TABLE A、ID(主键)-> TABLE B、AID 之间创建关系时,出现错误。

TABLE一个

ID | NAME
1  | name01
2  | name02

TABLE B

ID | NAME   | AID
1  | name01 | 1
2  | name02 | -1
3  | name03 | -2

有没有办法解决这个问题?这是否意味着开发人员所做的全部,他们在 sql 中没有使用任何关系,他们在代码隐藏中控制一切。

谢谢

您需要将这些添加到您的参考资料中 table。像这样:

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;

然后就可以添加外键关系了:

alter table b add constraint fk_b_aid foreign key (aid) references a(id);

referential integrity 的总体思路正是您不能 有无效引用。

因此,这里最好的做法是将其吸收并手动清理。在其他 table 中创建缺失的条目,或删除记录。

您也可以忽略对现有数据的检查。如果您使用 sql server management studio 来创建关系,可以选择像此屏幕截图中那样执行此操作

希望对您有所帮助