Temp表中的SQL插入WHERE子句无法正常工作

时间:2014-10-19 21:15:19

标签: sql sql-server database tsql insert

我有一个问题。所以我有一个脚本从表中获取记录,删除重复项并添加到数量字段。但是只有当charID = 0时才需要这样做,此时它正在抓取所有项目记录并组合重复记录。这是脚本。您可以在select语句后看到Where语句。我究竟做错了什么?我也在使用Navicat

DECLARE @tempSum TABLE
      ( CustomerID INT,
        ItemID INT,
        Var1   INT,
        InventoryID INT,
        Quantity    INT)

-- Get the sum of quantity per Customer, Item and Var1
-- This also get the first InvetoryID, assuming that the smallest number is the first one
INSERT @tempSum
     ( CustomerID,
       ItemID,
       Var1,
       InventoryID,
       Quantity )
SELECT CustomerID,
       ItemID,
       Var1,
       MIN(InventoryID),
       SUM(Quantity)
  FROM UsersInventory
        WHERE CharID = 0 -- Isn't working?? 
  GROUP BY CustomerID,
          ItemID,
          Var1

BEGIN TRANSACTION
  -- Remove duplicate items
  DELETE usi
    FROM UsersInventory usi
           JOIN
         @tempSum       tmp ON tmp.CustomerID   = usi.CustomerID
                           AND tmp.ItemID       = usi.ItemID
                           AND tmp.Var1         = usi.Var1
                           AND tmp.InventoryID <> usi.InventoryID
-- This ensures all items get deleted that are didn't mark as our firsts
-- Update the quantity that we summed earlier
  UPDATE usi
     SET Quantity = tmp.Quantity
    FROM UsersInventory usi
           JOIN
        @tempSum        tmp ON tmp.CustomerID  = usi.CustomerID
                           AND tmp.ItemID      = usi.ItemID
                           AND tmp.Var1        = usi.Var1
                           AND tmp.InventoryID = usi.InventoryID

commit TRANSACTION

这是结构

InventoryID bigint
CustomerID  int
CharID  int
BackpackSlot    int
ItemID  int
LeasedUntil datetime
Quantity    int
Var1    int
Var2    int
Durability  int

0 个答案:

没有答案