根据外键在其主 table 中的值更新外键
Update a foreign key based it's value in it's primary table
给定以下两个相关的 tables SQL 查询如何更新给定客户名称的订单的客户键。
+----------+-------------+ +-------------+--------------+
| OrderKey | CustomerKey | | CustomerKey | CustomerName |
+----------+-------------+ +-------------+--------------+
| 700 | 1 | | 1 | 'Idle' |
| 701 | 2 | | 2 | 'Palin' |
| 702 | 2 | | 3 | 'McCain' |
+----------+-------------+ +-------------+--------------+
那么使用参数 @OrderKey=701
和 @CustomerName='McCain'
什么更新查询会将订单 701 的客户密钥更改为 3?或者客户端代码应该在两个查询中执行此操作,以防用户使用不在客户 table?
中的名称
将语句分成两步供 Access 处理。
DECLARE @CustomerKey int = (select CustomerKey from Customers where CustomerName = @CustomerName)
update order
set CustomerKey = @CustomerKey
where OrderKey = @OrderKey
假设您将 table 与 OrderKey 和 CustomerKey(我称其为 order_customer)用作联结点 table (http://en.wikipedia.org/wiki/Junction_table) 。您可以直接在 order_customer table 上发布 SQL 更新。
在这种情况下,因为您没有随身携带客户的钥匙。您可以在您的客户端中执行以下 2 个查询(您也可以使用 1 个查询,但您需要单独处理新的用户案例):
- Select 来自 Customer 的 CustomerKey,其中 CustomerName = 'McCain'
如果此语句 return 是 CustomerKey,您可以 运行 以下语句:
- 更新 Order_Customer 设置 CustomerKey = 其中 OrderKey = 701
如果语句 1 没有 return 值,则表示用户不存在,您必须使用新的 CustomerName 和生成的 CustomerKey 进行插入,并在语句 2 中使用生成的键。
假设连接 table 已正确创建,如果 OrderKey 或 CustomerKey 中的任何一个不作为主键存在,语句 2 将失败。
给定以下两个相关的 tables SQL 查询如何更新给定客户名称的订单的客户键。
+----------+-------------+ +-------------+--------------+
| OrderKey | CustomerKey | | CustomerKey | CustomerName |
+----------+-------------+ +-------------+--------------+
| 700 | 1 | | 1 | 'Idle' |
| 701 | 2 | | 2 | 'Palin' |
| 702 | 2 | | 3 | 'McCain' |
+----------+-------------+ +-------------+--------------+
那么使用参数 @OrderKey=701
和 @CustomerName='McCain'
什么更新查询会将订单 701 的客户密钥更改为 3?或者客户端代码应该在两个查询中执行此操作,以防用户使用不在客户 table?
将语句分成两步供 Access 处理。
DECLARE @CustomerKey int = (select CustomerKey from Customers where CustomerName = @CustomerName)
update order
set CustomerKey = @CustomerKey
where OrderKey = @OrderKey
假设您将 table 与 OrderKey 和 CustomerKey(我称其为 order_customer)用作联结点 table (http://en.wikipedia.org/wiki/Junction_table) 。您可以直接在 order_customer table 上发布 SQL 更新。
在这种情况下,因为您没有随身携带客户的钥匙。您可以在您的客户端中执行以下 2 个查询(您也可以使用 1 个查询,但您需要单独处理新的用户案例):
- Select 来自 Customer 的 CustomerKey,其中 CustomerName = 'McCain'
如果此语句 return 是 CustomerKey,您可以 运行 以下语句:
- 更新 Order_Customer 设置 CustomerKey = 其中 OrderKey = 701
如果语句 1 没有 return 值,则表示用户不存在,您必须使用新的 CustomerName 和生成的 CustomerKey 进行插入,并在语句 2 中使用生成的键。
假设连接 table 已正确创建,如果 OrderKey 或 CustomerKey 中的任何一个不作为主键存在,语句 2 将失败。