Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI i had a strange requirement (never seen before) where i need to update a row with one id to update a row with other id in same table let me explain i have a table like

ID   Name   Comm    Fees
1    abc    23.5     1.2
1    xyz    56.5     2.4
2    abc     2.3      62.95
2    xyz     4.3     11.89


so what i need to do here is i have to update the 1st ID Comm row with 2nd ID Fees row , is it possible to do a update values from the same table the output should look like
ID   Name   Comm    Fees
1    abc    62.95     1.2
1    xyz    11.89     2.4
2    abc     2.3      62.95
2    xyz     4.3     11.89



Thanks in advance
Posted
Comments
dan!sh 12-Apr-11 21:46pm    
1. Do you want only the first row with name "abc" to be updated?
2. Do you want to do it for entire table or just some specific name which user will input?

1 solution

If the connecting column is Name then something like:
UPDATE MyTable
SET Comm = (SELECT Fees 
            FROM MyTable mt2
            WHERE mt2.Name = MyTable.Name
            AND mt2.Id != MyTable.Id)

However that fails if you have more than 2 rows with the same name so the condition in that case should be expanded.
 
Share this answer
 
Comments
Espen Harlinn 12-Apr-11 16:47pm    
Nice reply - 5ed!
Wendelius 12-Apr-11 16:59pm    
Thanks, even though it isn't yet working :)
makwith9789 12-Apr-11 16:48pm    
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

eRROR I AM GETTING
Wendelius 12-Apr-11 16:58pm    
This is what I warned about. So you have data like:
ID Name Comm Fees
1 abc 62.95 1.2
1 xyz 11.89 2.4
2 abc 2.3 62.95
2 xyz 4.3 11.89
3 abc 2.3 1.23
3 xyz 4.3 3.21

Q1: Now, should only the row with id 1 be updated?
Q2: Should id 1 row be updated with id2 row (with corresponding name) or with the sum of other rows?

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