Reputation: 2917
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?
Upvotes: 0
Views: 60
Reputation: 380
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
Upvotes: 1
Reputation: 326
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):
If this statement returns a CustomerKey, you can run the following statement:
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.
Upvotes: 1