带左连接的sql update函数

时间:2016-06-02 22:12:48

标签: sql ms-access

我在编写sql update函数时遇到了一些麻烦。我有一个报价表和第二个与这些报价相关的产品表。我试图根据产品设置具有某些$值的报价的所有状态。我似乎无法正确格式化此查询(下面的代码)。我知道在删除该部分之前,代码仅限于1个ID,目前正尝试使用1进行测试。

sqlStringUpdate = "UPDATE fq SET fq.spQuoteStatus = 5 From factQuote fq (LEFT JOIN FactQuoteProduct as fqp on fq.spQuoteID=fqp.fk_spQuoteID) " & _
"WHERE fq.spQuoteID = 4844 and ((sum(fqp.ItemTotal) <2000 and fq.quoteDate < #" & firstset & "#) or ( fq.bu=3401 and sum(fqp.ItemTotal) <10000 and fq.quoteDate < #" & secondset & "# ) or ( fq.bu>3401 and sum(fqp.ItemTotal) <10000 and fq.quoteDate < #" & secondset & "#));"

错误代码:错误3075(查询表达式中的语法错误(缺少运算符)&#39; 5左连接事实QUOT产生为fq.spQUoteID上的fqp = fqp.fk_spQuoteID&#39;)

1 个答案:

答案 0 :(得分:0)

第一个问题是LEFT JOIN不应该在括号中。

第二个问题,你需要在更新前计算聚合,你可以用CTE语法解决这个问题,尝试这样的事情:

;with
fqp as (
    select fk_spQuoteID, sum(ItemTotal) sum_ItemTotal
    from FactQuoteProduct 
    group by fk_spQuoteID
)
UPDATE fq SET fq.spQuoteStatus = 5 
From factQuote fq 
LEFT JOIN fqp on fq.spQuoteID=fqp.fk_spQuoteID
WHERE fq.spQuoteID = 4844 
and (
    (fqp.sum_ItemTotal <2000 and fq.quoteDate < @firstset) 
    or ( fq.bu=3401 and fqp.sum_ItemTotal <10000 and fq.quoteDate < @secondset ) 
    or ( fq.bu>3401 and fqp.sum_ItemTotal <10000 and fq.quoteDate < @secondset )
    );

如果您不熟悉CTE语法,可以使用嵌套选择:

UPDATE fq SET fq.spQuoteStatus = 5 
From factQuote fq 
LEFT JOIN (
    select fk_spQuoteID, sum(ItemTotal) sum_ItemTotal
    from FactQuoteProduct 
    group by fk_spQuoteID
) as fqp on fq.spQuoteID=fqp.fk_spQuoteID
WHERE fq.spQuoteID = 4844 
and (
    (fqp.sum_ItemTotal <2000 and fq.quoteDate < @firstset) 
    or ( fq.bu=3401 and fqp.sum_ItemTotal <10000 and fq.quoteDate < @secondset ) 
    or ( fq.bu>3401 and fqp.sum_ItemTotal <10000 and fq.quoteDate < @secondset )
    );

这应该可以解决问题