Search code examples
sql-servert-sqlsql-server-2008batch-insert

T-SQL, Insert into with MAX()+1 in subquery doesn't increment, alternatives?


I have a query where I need to "batch" insert rows into a table with a primary key without identity.

--TableA
--PK int (Primary key, no-identity)
--CustNo int
INSERT INTO TableA (PK,CustNo)
  SELECT (SELECT MAX(PK)+1 AS PK FROM TableA), CustNo
  FROM Customers

(simplified example - please don't comment about possible concurrency issues :-))

The problem is that it doesn't increment the PK "for each" processed row, and I get a primary key violation.

I know how to do it with a cursor/while loop, but I would like to avoid that, and solve it in a set-based kind of manner, if that's even possible ?

(running SQL Server 2008 Standard)


Solution

  • Declare @i int;
    
    Select @i = max(pk) + 1 from tablea;
    
    INSERT INTO TableA (PK, custno)
    Select row_number() over(order by custno) + @i  , CustNo
    FROM Customers