编写查询以交换SQL Server中的表中的值?

时间:2016-01-30 12:10:33

标签: sql sql-server

我错误地在表行中插入了错误的数据,现在我想交换数据。 男性代替女性,反之亦然。

enter image description here

以下是我期待的正确数据 -

enter image description here

4 个答案:

答案 0 :(得分:8)

简单更新有效:

UPDATE myTable
SET 
col1 = CASE WHEN col1 = 'male' THEN 'female' ELSE 'male' END,
col2 = CASE WHEN col2 = 'female' THEN 'male' ELSE 'female' END

结果:行值将为交换。

我希望,它会对你有用。

答案 1 :(得分:2)

您可以使用:

UPDATE table_name
SET Gender = CASE Gender
                  WHEN 'Male' THEN 'Female'
                  WHEN 'Female' THEN 'Male'
                  ELSE Gender
             END;

LiveDemo

请注意,male/femaleN/A之外的其他值将保持不变。

如果您只想为指定的名称使用:

NULL

答案 2 :(得分:0)

我不明白为什么您想要一个临时表,如果可以通过一次更新就可以做到这一点

但这也许符合您的需求

SELECT TOP 0 * 
INTO #tmp 
FROM YourTable

UPDATE T
SET gender = 'male'
OUTPUT Inserted.* INTO #tmp
FROM YourTable T
WHERE gender = 'female'

UPDATE T
SET gender = 'female'
FROM YourTable
WHERE gender = 'male' --Irrelevant for this case but assuming that you have different values
AND NOT EXISTS (SELECT 1 FROM #Temp WHERE name = T.name) -- Exclude the "swapped" records

或者您可能只是想让临时表在更改之前确认更改...。我正在尝试

DECLARE @swap1 VARCHAR(20) = 'male', @swap2 VARCHAR(20) = 'female'

SELECT * 
INTO #tmp
FROM YourTable

UPDATE #tmp 
    SET gender = CASE 
        WHEN gender = @swap1 THEN @swap2 
        WHEN gender = @swap2 THEN @swap1 
        ELSE gender END

SELECT * FROM #tmp

UPDATE A
SET Gender = T.gender
FROM YourTable A
JOIN #tmp T ON A.name = T.name

DROP TABLE #tmp

答案 3 :(得分:0)

使用以下脚本在2行之间交换值

IF OBJECT_ID('tempdb..#TempTable') IS NOT NULL DROP TABLE #TempTable

CREATE TABLE #TempTable
(
     ROW_ID INT IDENTITY(1,1),
     SEQUENCE_NO    INT,
     ID INT
)

DECLARE @Id INT = 24780, --Row Id

DECLARE @NewPosition INT = -1; -- (Move Up or Move Down +1 for Up and -1 For Down)
DECLARE @SEQUENCE_NO INT = 0;  

INSERT INTO #TempTable
SELECT  SEQUENCE_NO ,ID
            FROM TABLE_NAME S
    WHERE ID = @Id 

SET @SEQUENCE_NO = (SELECT SEQUENCE_NO FROM #TempTable)

INSERT INTO #TempTable
SELECT  SEQUENCE_NO AS SNO,ID
            FROM TABLE_NAME S
    WHERE ID  <> @Id   
    AND SEQUENCE_NO = (@SEQUENCE_NO + @NewPosition) -- (Move Up or Move Down +1 for Up and -1 For Down)

--Add check point here temp table to have 2 exact records 

;WITH x AS (SELECT  ID, SEQUENCE_NO FROM #TempTable WHERE ROW_ID = 1)   
   , y AS (SELECT ID, SEQUENCE_NO FROM #TempTable  WHERE ROW_ID = 2) 
UPDATE #TempTable
SET    SEQUENCE_NO = z.SEQUENCE_NO
FROM  (
   SELECT x.ID, y.SEQUENCE_NO FROM x,y
   UNION  ALL
   SELECT y.ID, x.SEQUENCE_NO FROM x,y
   ) z
WHERE #TempTable.ID = z.ID;


UPDATE SI
    SET SI.SEQUENCE_NO = T.SEQUENCE_NO -- (Swap Values here)
    FROM TABLE_NAME SI
        JOIN #TempTable T ON SI.ID = T.ID