Sql server 值必须存在于两个表中

Sql server 值必须存在于两个表中,sql-server,sql-server-2008,Sql Server,Sql Server 2008,我有两张桌子: create table customer ( cust_id cust_name ) create table customerphone ( customerphone_phone, cust_id, ) 客户id必须存在于两个表中,如何检查此项?将客户id作为表客户上的主键 然后在表custerphone上设置cust\u id外键,该外键指向customer上的cust\u id 然后,如果customer中已经存在cust\u id,则只能向customerphon

我有两张桌子:

create table customer
(
cust_id
cust_name
)

create table customerphone
(
customerphone_phone,
cust_id,
)

客户id必须存在于两个表中,如何检查此项?

客户id
作为表
客户
上的主键

然后在表
custerphone
上设置
cust\u id
外键,该外键指向
customer
上的
cust\u id


然后,如果
customer
中已经存在
cust\u id
,则只能向
customerphone
添加行。您可以使用cust\u idfromcustomer作为主键,并使用外键限制customerphone中的cust\u id

您可以使用本手册进行指导:

单凭声明性引用完整性(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

你考虑过外键吗?不,我不知道如何容易解释,但是每个客户都必须有一个客户电话,把客户电话放在客户桌上而不是在自己的桌子上。或者客户可以有多个电话号码?您不能强制要求记录必须存在于两个表中,因为您不能同时插入到两个表中(尽管存在事务)。不能要求记录必须存在于两个表中-任何DML语句(insert/UPDATE/DELETE/MERGE)一次只影响一个表。因此,有时一个值出现在一个表中,而不出现在另一个表中。你喜欢走哪条路?