简体   繁体   中英

Update a foreign key based it's value in it's primary table

Given the following two related tables how can an SQL query update a customer key of an order given the customer name.

+----------+-------------+    +-------------+--------------+
| OrderKey | CustomerKey |    | CustomerKey | CustomerName |
+----------+-------------+    +-------------+--------------+
|      700 |           1 |    |           1 | 'Idle'       |
|      701 |           2 |    |           2 | 'Palin'      |
|      702 |           2 |    |           3 | 'McCain'     |
+----------+-------------+    +-------------+--------------+

So with parameters @OrderKey=701 and @CustomerName='McCain' what update query would change customer key of order 701 to 3? Or should the client code perform this in two queries in case a users use a name that isn't in the customer table?

Broke statement into two steps for Access to handle.

DECLARE @CustomerKey int = (select CustomerKey from Customers where CustomerName = @CustomerName)

update order 
set CustomerKey = @CustomerKey
where OrderKey = @OrderKey

Assuming you are using the table with the OrderKey and CustomerKey (let me call this order_customer) as a junction table ( http://en.wikipedia.org/wiki/Junction_table ) . You can just issue a SQL update on the order_customer table directly.

In this case, since you don't have the key for the Customer with you. You can possibly do the following 2 queries in your client (You can also do with 1 query, but you will need to handle the new user case separately then):

  1. Select CustomerKey from Customer where CustomerName = 'McCain'

If this statement returns a CustomerKey, you can run the following statement:

  1. Update Order_Customer set CustomerKey = where OrderKey = 701

If statement 1 does not return a value, it means the user does not exist, and you have to do an insert with the new CustomerName and a generated CustomerKey and use this generated key in statement 2.

Assuming the junction table is properly created, statement 2 will fail if any of OrderKey or CustomerKey does not exist as a primary key already.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM