T-SQL语法问题如果是样式逻辑,则为问题

时间:2010-04-23 14:52:59

标签: sql-server tsql

今天有两个问题,我是一个忙碌的蜜蜂,幸运的是我有一个很棒的社区供我使用!

我的问题是:

我有一个字段,我需要根据现有的字段数据进行更新。

If Gender = F then foo = 1

If Gender = M then foo = 2

If Gender = Male then foo = 2

If Gender = Female then foo = 1

If Gender is not above then foo = 3

这就是我所拥有的:

update EmailAddresses 
set Priority1 = '1'
where GENDER__C = 'Female'

update EmailAddresses 
set Priority1 = '2'
where GENDER__C = 'Male'

update EmailAddresses 
set Priority1 = '1'
where GENDER__C = 'F'

update EmailAddresses 
set Priority1 = '2'
where GENDER__C = 'M'

update EmailAddresses 
set Priority1 = '3'
where GENDER__C not in (select 'Female', 'Male', 'F', 'M')

任何帮助非常感谢!它的星期五!!喔喔

2 个答案:

答案 0 :(得分:4)

将其更改为CASE声明:

UPDATE EmailAddresses
SET Priority1 = Case
    When GENDER_C IN ('Female', 'F') Then '1'
    When GENDER_C IN ('Male', 'M') Then '2'
    Else '3'
End
FROM EmailAddresses

答案 1 :(得分:3)

update EmailAddresses set
    Priority1 = case GENDER__C
        when 'Female' then 1
        when 'F' then 1        
        when 'Male' then 2
        when 'M' then 2
        else 3 end