Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 458
KorsG Avatar asked Aug 08 '11 15:08

KorsG


People also ask

How do you select the maximum 1 value in SQL?

Use the MAX function. the Max-1 value from the records. me know if you have any difficulty. You can use this select from where columnname=(select max(columnname) from where columnname=( select max(columnname) from ));

What is Max () +1 SQL?

MAX(x) - 1 simply means the max value of x in the table minus one. You can always use parenthesis and aliases ( as some_cool_name ) to make thing clearer, or to change names in the result. But the first syntax is perfectly valid.

Can we use top in subquery in SQL?

The rule checks for joined subqueries which return a limited by TOP clause number of rows. when a subquery with TOP is used. Rule has no parameters. The rule does not need Analysis Context or SQL Connection.

Which is faster insert into or select into?

INTO' creates the destination table, it exclusively owns that table and is quicker compared to the 'INSERT … SELECT'. Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage.


2 Answers

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
like image 149
Michael Buen Avatar answered Sep 26 '22 02:09

Michael Buen


+1 to Michael Buen, but I have one suggestion:

The table "tablea" can be empty, so we should write:

Select @i = isnull(max(pk),0) + 1 from tablea;

This will prevent a null error when trying to use this code.

like image 36
Max Avatar answered Sep 25 '22 02:09

Max