Swap two columns between two tables

时间:2015-09-01 22:30:16

标签: sql-server sql-server-2012

I have two tables: Jobs:

JobId   ApiId1   JobType
1       3        1
2       4        3
3       6        3

And TypeThreeJobs, for type-specific data

JobId   ApiId2
2       5
3       7

Where applicable, I need to swap the values in Api2 and Api3

JobId   ApiId1   JobType | ApiId2
1       3        1       |
2       5        3       | 4
3       7        3       | 6

What's the most efficient way to do this? I have an answer below, but was wondering if there was a more efficient version (e.g. no need for table variables).

1 个答案:

答案 0 :(得分:0)

My working solution is to use a table variable:

INSERT INTO @SwapValues
SELECT Jobs.JobId, ApiId1, ApiId2
FROM Jobs INNER JOIN TypeThreeJobs
ON Jobs.JobId = TypeThreeJobs.JobId

UPDATE Jobs
Set ApiId1 = SV.ApiId2
FROM @SwapValues SV INNER JOIN Jobs
ON Jobs.JobId = SV.JobId

UPDATE TypeThreeJobs
Set ApiId2 = SV.ApiId1
FROM @SwapValues SV INNER JOIN Jobs
ON Jobs.JobId = SV.JobId