Click here to Skip to main content
15,884,237 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have following Account table

Acct_ID     AM_ID    DM_ID    Userfield
111          1          2         Null
123          3          4         Null
321          5          6         Null
and so on....

I want to Update AM_ID in DM_ID and DM_ID in Userfield.
Please let me know how can i do it.
Here Acct_ID is primary Key.
What can be possible Update Query.
Posted
Updated 7-Oct-14 6:00am
v2
Comments
Herman<T>.Instance 7-Oct-14 11:15am    
What have you tried?
[no name] 7-Oct-14 11:46am    
where is your query

Your English isn't clear, but if I understand that you want to set the DM_ID field to the AM_ID value and the UserField to the DM_ID value? If so:
SQL
UPDATE Account
SET DM_ID = AM_ID, Userfield = DM_ID


This updates all rows. If you want to update a specific row:
SQL
UPDATE Account
SET DM_ID = AM_ID, Userfield = DM_ID
WHERE Acct_ID = SomeValue
 
Share this answer
 
Comments
Maciej Los 7-Oct-14 13:02pm    
+5!
Have a look at my answer ;)
King Fisher 8-Oct-14 0:43am    
clear one . +5
I'm not sure understand you correctly, but..

Below query replaces NULL in UserField with DM_ID values.
SQL
UPDATE t1 SET t1.Userfield = t2.DM_ID, t1.DM_ID = t2.AM_ID 
FROM dbo.Account AS t1 INNER JOIN Account AS t2 ON t1.Acct_ID = t2.Acct_ID



Fully working sample:
SQL
DECLARE @Account TABLE (Acct_ID INT, AM_ID INT, DM_ID INT, Userfield INT NULL)

INSERT INTO @Account (Acct_ID, AM_ID, DM_ID)
VALUES(111, 1, 2),
(123, 3, 4),
(321, 5, 6)

SELECT *
FROM @Account

UPDATE t1 SET t1.Userfield = t2.DM_ID, t1.DM_ID = t2.AM_ID
FROM @Account AS t1 INNER JOIN @Account AS t2 ON t1.Acct_ID = t2.Acct_ID

SELECT *
FROM @Account



Results:
1. query
111 1   2   NULL
123 3   4   NULL
321 5   6   NULL


2. query
111 1   1   2
123 3   3   4
321 5   5   6
 
Share this answer
 
v2
Comments
PhilLenoir 7-Oct-14 14:21pm    
You know that you don't need the join back to itself (unless you were copying one row's data to another), at least in an ACID DBMS? The results are the same for both solutions in, say, SQL Server! I guess that there may be a DBMS where you need the join. :)
Maciej Los 7-Oct-14 14:39pm    
Yes, i know, but - based on my experience - the questioners frequently asking how to update data based on values stored in another table.
Anyway, thank you for your valuable remark.
PhilLenoir 7-Oct-14 14:42pm    
No problem. It's good to show newbies a reflexive join anyway.

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