Question

I have a table that has a unique ID column which is an int. This doesn't necessarily contain all numbers up to the maximum, some are missed out (it isn't an identity column - out of my control).

I need to SELECT some existing lines from that table and add them to the end changing one column's data, with each row having a new ID, incrementing up from the MAX ID. Something like this:

declare @maxID int;
set @maxID = (select MAX("ID") from "table");

insert into "table"
select @maxID + ROW_NUMBER, 'newData', "col3", "col4"
from "table" where "col2" = 'oldData';

However, I'm not sure where to take it from here - the ROW_NUMBER requires an OVER statement which I honestly don't understand in this context.

Any help?

Was it helpful?

Solution

You need to put order of which ROW_NUMBER will generate numbers. Existing ID is good option here.

declare @maxID int;
set @maxID = (select MAX("ID") from "table");

insert into "table"
select @maxID + ROW_NUMBER OVER (ORDER BY "ID"), 'newData', "col3", "col4"
from "table" where "col2" = 'oldData';

OTHER TIPS

In its simplest sense the OVER clause just specifies what column to order the rows in

ROW_NUMBER() OVER( ORDER BY [primarykey]) 

will give you a 'gap free' surrogate primary key

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top