在存在的情况下更新使用案例(不能得到正确的结果)

时间:2014-09-22 09:43:27

标签: sql sql-server-2008 tsql sql-update business-intelligence

我试图更新一个由2个流量计算的表,第一个我必须使FillRateCode(我想要更新的列)等于来自BWH_OTC_Order的FillRateCode但是对于第二个流我说它等于到' -1'

这是我的剧本:

use BITS
;with tmp as ( 
select SalesOrderItemNum, SalesOrderNum, FillRateCode
From
BWH_OTC_Order
INNER JOIN REF_Company Comp
ON (Comp.CompanyCode= BWH_OTC_Order.CompanyCode AND Comp.DivisionCode='TEE')
where RevisedPGIDate is not null
)

UPDATE bits_tee.dbo.DMT_TEE_OTC_OrderFulFill
SET FillRateCode = case when  exists ( select 1 from tmp) then tmp.FillRateCode else '-1' end
FROM bits_tee.dbo.DMT_TEE_OTC_OrderFulFill DMT
left outer join tmp
on tmp.SalesOrderItemNum = DMT.SalesOrderItemNum
and tmp.SalesOrderNum = DMT.SalesOrderNum

这是我得到的结果

NB           BWH_FillRateCode   DMT_FillRateCode
124457       NULL               NULL
73991        0                  0
457507       1                   1
28632       -1                  -1
4849         2                   2
34262       3                    3

对于nulls,正确的resault是获得' -1'在DMT_FillRateCode

任何问题?

通过advence

2 个答案:

答案 0 :(得分:0)

也许我误解了你的问题,但是如果你只想用-1替换空值你可以使用isnull函数

isnull(tmp.FillRateCode,-1) -- I'm guessing the -1 is an int, and not a char '-1'

而不是

case when  exists ( select 1 from tmp) then tmp.FillRateCode else '-1' end

答案 1 :(得分:0)

您可以使用ISNULLCOALESCENULL替换为其他内容。你的exists( select 1 from tmp)是没有意义的,因为它只会检查是否有任何行(所以不仅仅是相关的行)。

WITH tmp 
     AS (SELECT SalesOrderItemNum, 
                SalesOrderNum, 
                FillRateCode 
         FROM   BWH_OTC_Order 
                INNER JOIN REF_Company Comp 
                        ON ( Comp.CompanyCode = BWH_OTC_Order.CompanyCode 
                             AND Comp.DivisionCode = 'TEE' ) 
         WHERE  RevisedPGIDate IS NOT NULL) 
UPDATE DMT 
SET    DMT.FillRateCode = ISNULL(tmp.FillRateCode, '-1') 
FROM   bits_tee.dbo.DMT_TEE_OTC_OrderFulFill DMT 
       LEFT OUTER JOIN tmp 
                    ON tmp.SalesOrderItemNum = DMT.SalesOrderItemNum 
                       AND tmp.SalesOrderNum = DMT.SalesOrderNum