更新查询不保存正确的值

时间:2014-01-08 23:31:56

标签: sql-server-2008

我正在尝试创建一个使用查询

的UPDATE查询

ChargeTransaction和ChargeError之间存在1> M关系 ChargeBody是一个包含json的TEXT字段。

当我运行内部查询时,我得到一个不同的chargetransactionids和帐户ID列表(1 2和3),但是当我把它放入UPDATE语句时,它会为所有的chargetransactions分配一个3的accountid。

UPDATE ChargeTransaction
    SET AccountId= a.AccountID
FROM 
    (   
        SELECT ChargeTransactionId, AccountID
        FROM 
        (
            SELECT 
                  [ChargeTransactionId],
                  CASE WHEN ChargeBody LIKE '%"ReceivingFacility":"998001"%' THEN 1 
                       WHEN ChargeBody LIKE '%"ReceivingFacility":"998002"%' THEN 2
                       WHEN ChargeBody LIKE '%"ReceivingFacility":"998003"%' THEN 3
                       ELSE 1
                  END AS AccountId,
                  ChargeBody
              FROM [ChargesDashboard].[dbo].[ChargeError]
         ) b
         GROUP BY ChargeTransactionId, AccountId
     ) a
WHERE ChargeTransactionId=a.ChargeTransactionId ;

2 个答案:

答案 0 :(得分:2)

这可能不是最优雅但我觉得它会起作用。我认为问题是你想要一个连接到你的派生表。

with myCte as
(
SELECT ChargeTransactionId, AccountID
        FROM 
        (
            SELECT 
                  [ChargeTransactionId],
                  CASE WHEN ChargeBody LIKE '%"ReceivingFacility":"998001"%' THEN 1 
                       WHEN ChargeBody LIKE '%"ReceivingFacility":"998002"%' THEN 2
                       WHEN ChargeBody LIKE '%"ReceivingFacility":"998003"%' THEN 3
                       ELSE 1
                  END AS AccountId,
                  ChargeBody
              FROM [ChargesDashboard].[dbo].[ChargeError]
         ) b
         GROUP BY ChargeTransactionId, AccountId
)

UPDATE C
set AccountID = myCte.AccountID 
from ChargeTransaction C
    inner join myCte on C.ChargeTransactionId  = myCte.ChargeTransactionId

答案 1 :(得分:0)

原来问题是ChargeTransaction表没有ChargeTransactionId字段,它有一个Id字段

UPDATE ChargeTransaction
    SET AccountId= a.AccountID
FROM 
    (   
        SELECT ChargeTransactionId, AccountID
        FROM 
        (
            SELECT 
                  [ChargeTransactionId],
                  CASE WHEN ChargeBody LIKE '%"ReceivingFacility":"998001"%' THEN 1 
                       WHEN ChargeBody LIKE '%"ReceivingFacility":"998002"%' THEN 2
                       WHEN ChargeBody LIKE '%"ReceivingFacility":"998003"%' THEN 3
                       ELSE 1
                  END AS AccountId,
                  ChargeBody
              FROM [ChargesDashboard].[dbo].[ChargeError]
         ) b
         GROUP BY ChargeTransactionId, AccountId
     ) a
WHERE ChargeTransaction.Id=a.ChargeTransactionId ;