Click here to Skip to main content
15,898,373 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a table name: Colors.

Colors:
ID(PrimaryKey,Identy)| Position | Color_Name
                             |            |
               1                  1               Red
               2                  2               Black
               4                  3               Blue
               5                  5               Purple
               8                  6               Pink

Now, when i going to insert a row having '2' as Position and 'Yellow' as Color_Name.

I have to reset position value of all rows of a table,insert the new row(2,Yellow) and need the following result in table.

ID(PrimaryKey,Identy)| Position | Color_Name
                             |            |
               1                  1               Red
               2                  3               Black
               4                  4               Blue
               5                  5               Purple
               8                  6               Pink
               9                  2               Yellow

How can i do this in a store procedure? or tell me the steps with SQL-statements to do this.

Thanks in advance.
Posted
Updated 11-May-11 19:51pm
v2
Comments
tanishtaman 12-May-11 0:05am    
Note: please note how 'Position' column is reseting.

IMO, your logic flow would be something as follows -

Decide the position of the new color.
Scan through the list to see if that position is already taken by another color.
If no, then easy - just insert your record with this position.
If yes, then update the rows of all colors where position is greater than or equal to this position (incrementing position by 1).
Insert the current color now.


Good luck!
 
Share this answer
 
Comments
tanishtaman 12-May-11 1:03am    
Thanks for your reply. Note the position of just Black,Blue color is incremented else not. Because, in first table there was no row having position 4, this fills that position too. Please write sql-statements too.
in SP follow below steps:

1.first find its already existed having postion 2
script : select * from Colors where position=2;
insert into Colors (position,color_name) values(2,Yellow);
if find then
run this script : update Colors set position=position+1;
else
run this script: insert into Colors (position,color_name) values(2,Yellow);
end


now run this script again: select * from Colors; you will see td row .
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900