0

我在存储过程中有一个临时表。

我正在做的是从不同的表中获取数据并将其插入到临时表中

INSERT INTO #TempTable
  SELECT * FROM t1
  INNER JOIN t2 ON t1.ID = t2.ID

插入后,我需要更新一列。在更新临时表之前,我想按另一列对临时表数据进行排序。

如何ORDER By在临时表的更新子句之前应用子句?

4

1 回答 1

0

确保您的临时表有一个 IDENTITY 字段。

CREATE TABLE #TempTable 
(
  ID int identity(1,1) primary key
  ...
)

在您的初始插入时下订单:-

INSERT INTO 
  #TempTable
SELECT * FROM t1
INNER JOIN 
  t2 
ON t1.ID = t2.ID
ORDER BY [Your Field]

基本原理:- 有些人可能会争辩说没有必要将标识字段放入其中,或者实际上临时表中行的顺序并不重要。我不同意。

首先,拥有一个 ID 字段允许您进行如下连接:-

SELECT 
   t1.*, t2.SpecificThing
FROM
   #TempTable t1
INNER JOIN
   #TempTable t2
ON  t1.ID = ( t2.ID + 1)

这对于任何运行总计/累积技巧都很方便。

至于在临时表中排序不重要,我不同意 - 至少在SQL Server上。SQL Server 上的 UPDATE 语句按顺序更新行。如果没有,这个迷人的(并且非常快速的)运行总技巧将永远不会奏效。

CREATE TABLE #CustomerInfo 
(
   ID int identity(1,1) primary key,
   CustomerId int,
   SaleValue money,
   RunningTotal money
)

-- Assume customer is populated

DECLARE @RunningTotal decimal(18,4)
DECLARE @CustomerId INT

SELECT @CustomerId = CustomerId FROM #CustomerInfo WHERE Id = 1
SET @RunningTotal = 0

-- This only works in SQL Server because under the hood, the engine is updating
-- iteratively in order.
-- 
-- Starts at row 0, then row 1 - with each row the value of @RunningTotal
-- is reassigned.
UPDATE #CustomerInfo
SET 
   @RunningTotal = 
   RunningTotal = 
   CASE WHEN 
      -- Are we still looking at the same customer?
      @CustomerId = CustomerId 
   THEN 
     -- Yes. Add sale value to @RunningTotal
     @RunningTotal + SaleValue
   ELSE
     -- No, reset @RunningTotal to SaleValue of this row
     SaleValue
   END 
   ,@CustomerId = CustomerId
 FROM #CustomerInfo 
于 2012-11-07T13:40:47.760 回答