更新表变量,而不在T-SQL中复制数据

问题描述 投票:3回答:2

我有2个表变量@Items@Locations。这两个表都包含一个用于项目和位置的卷列。

我正在尝试以每件物品的可用容量来检索位置。如果该位置没有足够的容量容纳其他任何物品,我希望将该位置排除在结果之外。目的是根据卷的可用位置更新@Items,如果无法存储更多项目,则忽略该位置。

这是我为这种情况编写的T-SQL:

DECLARE @Items TABLE
(
    Id INT,
    Reference NVARCHAR(255),
    Volume DECIMAL(18, 4),
    IdLocation INT
)

DECLARE @Locations TABLE
(
    Id INT,
    Reference NVARCHAR(255),
    Volume DECIMAL(18, 4)
)

INSERT INTO @Locations (Id, Reference, Volume)
    SELECT 100, 'Location 1', 50000
    UNION SELECT 101, 'Location 2', 100000
    UNION SELECT 102, 'Location 3', 300000

INSERT INTO @Items (Id, Reference, Volume)
    SELECT 1, 'Item 1', 50000
    UNION SELECT 2, 'Item 2', 50000
    UNION SELECT 3, 'Item 3', 100000
    UNION SELECT 4, 'Item 4', 100000
    UNION SELECT 5, 'Item 5', 300000
    UNION SELECT 6, 'Item 6', 300000
    UNION SELECT 7, 'Item 7', 300000

UPDATE I
SET I.IdLocation = (SELECT TOP 1 L.Id 
                    FROM @Locations L
                    WHERE L.Volume >= I.Volume)
FROM @Items I

SELECT *
FROM @Items

我得到的结果:

“

我期望得到的结果:

“

如果有人能解决这个问题,我将非常感谢。

sql-server tsql ssms temp-tables
2个回答
0
投票

可能有一种基于集合的聪明方法来完成此任务,其中涉及窗口函数和运行中的已分配总量。就个人而言,当必须像这样分配股票时,我经常会发现自己陷入了循环,例如

declare @Count int;

-- How many items are there to update?
select @Count = count(*) from @Items where IdLocation is null

while exists (select 1 from @Items where IdLocation is null) begin
  UPDATE I SET
    I.IdLocation = (
      SELECT TOP 1 L.Id 
      FROM @Locations L
      WHERE (L.Volume - coalesce((select sum(I1.Volume) from @Items I1 where I1.IdLocation = L.id),0)) >= I.Volume
    )
  FROM @Items I
  where I.id in (select top 1 id from @Items where IdLocation is null);

  -- Did we update any items? If not exit the loop as we have allocated all space.
  if @Count = (select count(*) from @Items where IdLocation is null) break;

  -- If so, update the new count for the next loop
  select @Count = count(*) from @Items where IdLocation is null;
end

SELECT *
FROM @Items;

-2
投票

您是否尝试过合并功能?它将解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.