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)
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 ));
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.
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.
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.
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
+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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With