Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Query as shown below column1 is int anothercolumn is varchar(100)

INSERT INTO TABLE1 (column1,column2)
SELECT (MAX(column1) FROM TABLE1)+1 ,anotherColumn FROM 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 I want

column1  column2
-------  -------
3         test1
4         test2
5         anotherVal1
6         anotherVal2
7         anotherVal3

How can I achieve this in SQLserver 2008 StoredProcedure? I always assumed that Queries are iterated and they would check the condition for each rows. But it seems like aggregate function executes only once!

EDIT 1

Please answer this too After only completing the SELECT statement the INSERT would work. Thats why I didn't get result as expected??? Am I correct?

like image 729
Subin Jacob Avatar asked Aug 10 '13 08:08

Subin Jacob


1 Answers

use row_number function to give your rows sequential numbers

insert into Table1 (column1,column2)
select 
    (select max(column1) from Table1) + row_number() over (order by T2.anotherColumn),
    T2.anotherColumn
from Table2 as T2

or more safe version (it would work even if you don't have any rows in Table1):

insert into Table1 (column1,column2)
select 
    isnull(T1.m, 0) + row_number() over (order by T2.anotherColumn),
    T2.anotherColumn
from Table2 as T2
    outer apply (select max(column) as m from Table1) as T1
like image 107
Roman Pekar Avatar answered Oct 03 '22 17:10

Roman Pekar