单个更新查询以在不使用CASE的情况下更新表

时间:2018-04-12 07:54:17

标签: sql sql-server

我有一个表名注册,列为:

Id         Name          Gender
1         Sanjay           F
2         Suhana           M
3         Ravi             F
4         Tanya            M

现在,我需要一个查询,在不使用CASE的情况下,在单个查询中将性别M更新为F,将F更新为M.

5 个答案:

答案 0 :(得分:2)

我在这里找到了另一个选项:https://dba.stackexchange.com/questions/125171/switching-values-in-a-column-with-one-update-statement

UPDATE YourTable
    SET Gender = CHAR(ASCII('M') + ASCII('F') - ASCII(Gender))
WHERE Gender IN ('M', 'F')

答案 1 :(得分:1)

不确定为什么不想使用case语句,如果使用sql server 2012 +

,可以使用IIF
update Registration set Gender = IIF(Gender = 'F','M','F')

答案 2 :(得分:0)

我无法想象为什么你不想要CASE,但你可以在下面的CTE更新中找到类似的结果(假设Id是主键)。

;WITH FemaleToMale AS
(
    SELECT
        R.Id,
        NewGender = 'M'
    FROM
        Registration AS R
    WHERE
        R.Gender = 'F'
),
MaleToFemale AS
(
    SELECT
        R.Id,
        NewGender = 'F'
    FROM
        Registration AS R
    WHERE
        R.Gender = 'M'
)
UPDATE R SET
    Gender = ISNULL(F.NewGender, M.NewGender)
FROM
    Registration AS R
    LEFT JOIN FemaleToMale AS F ON R.Id = F.Id
    LEFT JOIN MaleToFemale AS M ON R.Id = M.Id
WHERE
    F.Id IS NOT NULL OR M.Id IS NOT NULL

答案 3 :(得分:0)

第一个case表达式是有效的方法,但其他方式是通过查找

select id, Name, a.g2 as Gender 
from table t left join (
    values ('M', 'F'), ('F', 'M')
)a(g1, g2) on a.g1 = t.Gender

答案 4 :(得分:0)

我想这是测试中的一些问题。所以,为了在一个声明中这样做:

UPDATE @DataSource
SET [Gender] = REPLACE(REPLACE(REPLACE([Gender], 'M', 'X'), 'F', 'M'), 'X', 'F');

试试这个:

DECLARE @DataSource TABLE
(
    [ID] INT
   ,[Name] VARCHAR(12)
   ,[Gender] CHAR(1)
);

INSERT INTO @DataSource ([ID], [Name], [Gender])
VALUES (1, 'Sanjay', 'F')
      ,(2, 'Suhana', 'M')
      ,(3, 'Ravi', 'F')
      ,(4, 'Tanya', 'M');

SELECT *
FROM @DataSource;

UPDATE @DataSource
SET [Gender] = REPLACE(REPLACE(REPLACE([Gender], 'M', 'X'), 'F', 'M'), 'X', 'F');

SELECT *
FROM @DataSource;

enter image description here

执行此操作的另一种方法是使用IIFCASEREPLACE来将Gender转换为数字并使用CHOOSE。在这里,我使用ASCII函数执行此操作:

SELECT *
      ,CEILING(ASCII ([Gender]) % 10 * 0.1 + 1) AS [Char_To_Number]
      ,CHOOSE(CEILING(ASCII ([Gender]) % 10 * 0.1 + 1), 'M', 'F') AS [ValueSwitched]
FROM @DataSource;

UPDATE @DataSource 
SET [Gender] = CHOOSE(CEILING(ASCII ([Gender]) % 10 * 0.1 + 1), 'M', 'F');

enter image description here