Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Need Help with Insert query

Author  Topic 

MichelleMA
Starting Member

32 Posts

Posted - 2011-11-03 : 15:47:48

Can you please help with a way how to complete an insert statement, where one column of the destination table is the max of that column + 1

Insert into tableA (columnA1, columnA2, columnA3)

(Select ColumnB1, ColumnB2, [ MAX(ColumnA3) + 1 FROM tableA ]
From tableB)

Thank you,
Michele

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-11-04 : 04:26:35
[code]
Insert into tableA (columnA1, columnA2, columnA3)
Select ColumnB1, ColumnB2, (select MAX(ColumnA3) + 1 FROM tableA )
From tableB
[/code]



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

MichelleMA
Starting Member

32 Posts

Posted - 2011-11-04 : 19:07:00


Thank you Visakh.

I tried it but it keeps inserting the first calculated MAX(ColumnA3) for all inserted rows, while I am expecting the value to be incremented by 1 for each inserted row. I implemented it using a while loop on every row of table B, incrementing the variable for each iteration.

Thanks,
Michelle

Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2011-11-04 : 19:12:36
[code]
Select ColumnB1, ColumnB2, (select MAX(ColumnA3) FROM tableA ) + row_number() over(order by ColumnB1)
From tableB
[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page
   

- Advertisement -