I have to exchange the column data from one set of rows to another set of rows
Can anyone explain?
I have to exchange the column data from one set of rows to another set of rows
Can anyone explain?
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jayraj ChhayaPosted Dec 4, 2024, 6:22 AM
Hi Kiran Kumar,
To exchange column data between two sets of rows in SQL, you can utilize a temporary variable or a common table expression (CTE) to facilitate the swap. Below is a simple example using a temporary variable approach.
Assuming you have a table named
Employeeswith columnsID,Name, andSalary, and you want to exchange theSalaryvalues of two specific employees (e.g., IDs 1 and 2):This method ensures that the
Salaryvalues are exchanged without losing any data. Always ensure to back up your data before performing such operations to prevent any accidental data loss.Kiran KumarPosted Dec 4, 2024, 1:01 PM
Hi Mathews
Thanks for simplified it into single query but again it will update only one record by Id right, not the group of rows
Here is my table
All IT cells should be changed to Admin
And
All Admin cells should be changed to IT
Condition
There should not be any change in the Id column as its primary unique
This scenario where users have selected or entered different department by mistake and that need to be corrected
Please provide the query
Jaish MathewsPosted Dec 4, 2024, 9:59 AM
You ,may try using CASE as below, I didn't execute this though.
UPDATE Employees
Notes:SET Salary = CASE
WHEN ID = 1 THEN (SELECT Salary FROM Employees WHERE ID = 2)
WHEN ID = 2 THEN (SELECT Salary FROM Employees WHERE ID = 1)
END
WHERE ID IN (1, 2);
ID).SELECTstatements inside theCASEclause work correctly because the SQL engine evaluates them independently for each row before performing theUPDATE.Kiran KumarPosted Dec 4, 2024, 9:35 AM
Hi Jay
I accept your solution but is there any way we can get this done by not using temp table
Also, just for an update on the question I can see your code it update only specific column row value that is by id, but I need to exchange a set of rows to be updated example by departments within the same table
Example Data stored in the format of specific employee's designation not entered for specific department I want that to bring from another department's role and that department roles have to be updated by the charging first time department rows
It is kind of exchanges the same set of data bw rows for that particular group of rows