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.
Author |
Topic |
omnisysgroup
Starting Member
10 Posts |
Posted - 2008-01-23 : 15:10:40
|
I have an ordered product list table called ProductProduct OrderApples 1Oranges 2Peaches 3Lemons 4How do I write a SQL statement to insert the values of 'bananas' after 'oranges'? |
|
jdaman
Constraint Violating Yak Guru
354 Posts |
Posted - 2008-01-23 : 15:18:32
|
Is this your desired output?Product OrderApples 1Oranges 2Bananas 3Peaches 4Lemons 5 |
 |
|
omnisysgroup
Starting Member
10 Posts |
Posted - 2008-01-23 : 15:20:46
|
yes that is my desired output. |
 |
|
jdaman
Constraint Violating Yak Guru
354 Posts |
Posted - 2008-01-23 : 15:56:53
|
[code]DECLARE @Fruits TABLE ( [Product] CHAR(10), [Order] INT )INSERT @Fruits ( [Product], [Order] )SELECT 'Apples', 1 UNIONSELECT 'Oranges', 2 UNIONSELECT 'Peaches', 3 UNIONSELECT 'Lemons', 4UPDATE @FruitsSET [Order] = [Order]+1WHERE [Order]>(SELECT [Order] FROM @Fruits WHERE [Product] = 'Oranges')INSERT @Fruits ([Product], [Order])SELECT 'Bananas', [Order]+1FROM @FruitsWHERE [Product] = 'Oranges'SELECT * FROM @FruitsORDER BY [Order][/code] |
 |
|
omnisysgroup
Starting Member
10 Posts |
Posted - 2008-01-23 : 16:05:40
|
thanks much you are awesome...one more question now...say my table has a billion rows and this process becomes very resource intensive...how could i modify my table structure to better suit these type of updates? |
 |
|
jdaman
Constraint Violating Yak Guru
354 Posts |
Posted - 2008-01-23 : 16:11:28
|
Surely there must be a more logical column to order your data by than the Order column. What do you base your decision of what to set the Order column to? How do you decide that Bananas go before Peaches? |
 |
|
omnisysgroup
Starting Member
10 Posts |
Posted - 2008-01-23 : 16:15:44
|
it is an interview question so i have clue. |
 |
|
jdaman
Constraint Violating Yak Guru
354 Posts |
Posted - 2008-01-23 : 16:31:46
|
I would suggest doing some reading on indexes. |
 |
|
|
|
|