简体   繁体   中英

Ordered data before update in SQL Server 2008 R2

I have a temp table inside a stored procedure.

What I am doing is fetching data from different table and inserting it into temp table using

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

After inserting, I need to update one column. Before updating the temp table I want to order the temp table data by another column.

How can I apply ORDER By clause before update clause on temp table?

Make sure your temporary table has an IDENTITY field.

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

Put an order by on your initial insertion:-

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

Rationale:- Some may argue that putting the identity field in is unnecessary, or indeed that the order of the rows in the temp table is unimportant. I'd disagree.

First, having an ID field allows you to do joins like :-

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

Which can be handy for any running total / cumulation tricks.

As for ordering not being important in a temp table, I'd disagree - at least on SQL Server . The UPDATE statement on SQL Server updates rows in order . If it didn't, this fascinating (and very speedy) running total trick would never work.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM