值必须存在于两个表中

时间:2017-02-23 10:30:33

标签: sql-server sql-server-2008

我有两张桌子:

create table customer
(
cust_id
cust_name
)

create table customerphone
(
customerphone_phone,
cust_id,
)

cust_id必须存在于两个表中,我该如何检查?

3 个答案:

答案 0 :(得分:4)

单独使用声明性参照完整性(DRI)无法做到这一点。添加外键约束只是解决方案的一部分。您还需要将插入事务和业务逻辑包装到2个表中。我建议在存储过程中执行此操作,以便从应用程序的角度将其作为原子操作进行操作。

Begin Transaction
  Logic around inserting a Customer
  Logic around inserting CustomerPhone row
If the newly added Customer has a CustomerPhone
    Commit Transaction
Else
    Rollback Transaction

答案 1 :(得分:2)

在表cust_id上设置customer主键。

然后在表cust_id上设置customerphone个外键,该地址指向cust_id上的customer

如果customerphone中已存在cust_id,则只能向customer添加行。

答案 2 :(得分:0)

您可以使用客户中的 cust_id 作为PRIMARY KEY,并使用外键来限制 customerphone 中的 cust_id 强>

您可以使用本手册自我指导: https://technet.microsoft.com/en-us/library/ms175464(v=sql.105).aspx

相关问题