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

KorsG picture KorsG · Aug 8, 2011 · Viewed 40.9k times · Source

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)

Answer

Michael Buen picture Michael Buen · Aug 8, 2011
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