sql - How can I increment the value for each INSERT INTO iteration? -


i have query shown below column1 int anothercolumn varchar(100)

insert table1 (column1,column2) select (max(column1) table1)+1 ,anothercolumn table2 

table1 before query

column1  column2 -------  ------- 3         test1 4         test2 

table1 after query

column1  column2 -------  ------- 3         test1 4         test2 5         anotherval1 5         anotherval2 5         anotherval3 

but want

column1  column2 -------  ------- 3         test1 4         test2 5         anotherval1 6         anotherval2 7         anotherval3 

how can achieve in sqlserver 2008 storedprocedure? assumed queries iterated , check condition each rows. seems aggregate function executes once!

edit 1

please answer after completing select statement insert work. thats why didn't result expected??? correct?

use row_number function give rows sequential numbers

insert table1 (column1,column2) select      (select max(column1) table1) + row_number() on (order t2.anothercolumn),     t2.anothercolumn table2 t2 

or more safe version (it work if don't have rows in table1):

insert table1 (column1,column2) select      isnull(t1.m, 0) + row_number() on (order t2.anothercolumn),     t2.anothercolumn table2 t2     outer apply (select max(column) m table1) t1 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -