鉴于以下两个相关表,SQL查询如何更新给定客户名称的订单的客户密钥。
function getCatFact() {
var catFact = "";
request('http://catfacts-api.appspot.com/api/facts', function (error, resp, body) {
var jsonObj = JSON.parse(body);
catFact += jsonObj.facts[0];
})
console.log("HERE IT IS: "+catFact);
return "Here is your CatFact" + catFact;
}
因此,使用参数+----------+-------------+ +-------------+--------------+
| OrderKey | CustomerKey | | CustomerKey | CustomerName |
+----------+-------------+ +-------------+--------------+
| 700 | 1 | | 1 | 'Idle' |
| 701 | 2 | | 2 | 'Palin' |
| 702 | 2 | | 3 | 'McCain' |
+----------+-------------+ +-------------+--------------+
和@OrderKey=701
,更新查询会将订单701的客户密钥更改为3?或者客户端代码是否应该在两个查询中执行此操作,以防用户使用不在customer表中的名称?
答案 0 :(得分:1)
将声明分为两个步骤,以便进行处理。
DECLARE @CustomerKey int = (select CustomerKey from Customers where CustomerName = @CustomerName)
update order
set CustomerKey = @CustomerKey
where OrderKey = @OrderKey
答案 1 :(得分:1)
假设您正在使用带有OrderKey和CustomerKey的表(我将此order_customer称为联结表)(http://en.wikipedia.org/wiki/Junction_table)。您可以直接在order_customer表上发出SQL更新。
在这种情况下,由于您没有为客户提供密钥。您可以在客户端中执行以下2个查询(您也可以使用1个查询,但是您需要单独处理新的用户案例):
如果此语句返回CustomerKey,则可以运行以下语句:
如果语句1未返回值,则表示该用户不存在,您必须使用新的CustomerName和生成的CustomerKey进行插入,并在语句2中使用此生成的键。
假设正确创建了联结表,如果任何OrderKey或CustomerKey不存在作为主键,则语句2将失败。