更新不会产生正确的结果

时间:2013-02-25 19:32:30

标签: sql sql-server tsql sql-update

UPDATE @DList1
SET
Listed = a.Listed +  b.Listed,
Sold = b.Sold,
Volume = a.Volume + ISNULL(b.Volume, 0)
FROM @DList1 a, @DList2 b 
WHERE a.ItemID = b.ItemID

在上面更新的声明中,[Listed]列无法正确更新[Volume]

Dlist2

ItemID  Listed  Sold Volume
104     NULL    1    266000
778     1       1    5390
200     1       0    266000

Dlist1

ItemID  Listed  Sold Volume
200     1       0    6395000
779     1       0    155000

更新后@ Dlist1

ItemID  Listed  Sold Volume
200     1       0    6661000
779     1       0    155000

方案:

DECLARE @DList1 TABLE 
( 
    ItemID          NVARCHAR(20)
    , Listed        BIGINT
    , Sold          BIGINT
    , Volume        BIGINT
)

DECLARE @DList2 TABLE 
( 
      ItemID        NVARCHAR(20)
    , Listed        BIGINT
    , Sold          BIGINT
    , Volume        BIGINT
)

2 个答案:

答案 0 :(得分:3)

您需要将第一行更改为UPDATE a。通过这种方式,您告诉SQL您要更新的记录是DList1DList2ItemID匹配的记录(您正在更新相同的记录)您在下面提到的DList1

此外,使用连接语法而不是from a,b where...,因为它会导致查询更具可读性和可维护性:

UPDATE a
SET
  Listed = a.Listed +  b.Listed,
  Sold = b.Sold,
  Volume = a.Volume + ISNULL(b.Volume, 0)
FROM @DList1 a
JOIN @DList2 b 
  on a.ItemID = b.ItemID;

这是一个SQLFiddle链接:http://www.sqlfiddle.com/#!3/b8cfc/3

答案 1 :(得分:2)

加入两个表并进行更新,如果您 isnull() coalesce(),则请务必使用adding/concatenatingnullable fields ;

UPDATE a 
SET a.Listed = isnull(a.Listed, b.Listed),
    a.Sold = b.Sold,
    a.Volume = a.Volume + isnull(b.Volume, 0)
FROM @DList1 a join @DList2 b  on a.ItemID = b.ItemID

SQL-FIDDLE DEMO