1
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]

列表2

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

列表1

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
)
4

2 回答 2

3

您需要将第一行更改为UPDATE a. 这样,您告诉 SQL 您要更新的记录是与byDList1匹配的记录(您正在更新您在下面提到的相同)。DList2ItemIDDList1

此外,请使用连接语法,而不是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

于 2013-02-25T19:39:11.670 回答
2

加入两个表并更新并确保使用isnull()orcoalesce()如果您adding/concatenating使用nullable 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 演示

于 2013-02-25T19:39:21.153 回答