mhep
mhep

Reputation: 2139

INSERT INTO using SELECT and increment value in a column

I am trying to insert missing rows into a table. One of the columns is OrderNumber (sort number), this column should be +1 of the max value of OrderNumber returned for sID in the table. Some sIDs do not appear in the SPOL table which is why there is the WHERE clause at the end of the statement. I would run this statement again but set OrderNumber to 1 for the records where sID does not currently exist in the table.

The statement below doesn't work due to the OrderNumber causing issues with the primary key which is sID + OrderNumber.

How can I get the OrderNumber to increase for each row that is inserted based on the sID column?

INSERT INTO SPOL(sID, OrderNumber, oID)
   SELECT           
      sID, OrderNumber, oID
   FROM
      (SELECT 
           sID, 
           (SELECT Max(OrderNumber) + 1
            FROM SPOL
            WHERE sID = TMPO.sID) AS OrderNumber, 
           oID
       FROM TMPO
       WHERE NOT EXISTS (SELECT * FROM SPOL
                         WHERE SPOL.oID = TMPO.oID)
      ) AS MyData
   WHERE
       OrderNumber IS NOT NULL  

Upvotes: 4

Views: 11962

Answers (2)

Bridge
Bridge

Reputation: 30651

It's much better to handle this in the database design with an identity column - you don't mention whether or not you can change the schema but hopefully you can as queries will end up a lot cleaner if you don't have to manage it yourself.

You can set the Identity property to on for your OrderNumber column in SQL Server management studio, but the script it would generate clones the table with the new specification, inserts the values you've already got with Identity_Insert on, drops the original table, and renames the temporary one to replace it - this has massive overheads depending on how many rows you've got.

The most efficient way to go about it is probably:

  1. create an additional column with the identity property on
  2. copy across the values
  3. rename the original column
  4. rename the new column to the same name as the original
  5. remove the original OrderNumber column

Once it's done, it's done though - and looks after itself. Wouldn't you rather your insert statement simply said something like this:

INSERT INTO SPOL (sID, oID)
SELECT sID, oID,
FROM   TMPO
WHERE  OrderNumber IS NOT NULL

Upvotes: 2

Teju MB
Teju MB

Reputation: 1383

Use identity(1,1) to increment your column Order Number,this would makes your task easy..!

Upvotes: 0

Related Questions