在case语句中将varchar转换为int

时间:2017-08-14 13:32:01

标签: sql sql-server-2012

我正在尝试将1,2 ... 5转换为Main.District 1,Main.District 2 ... Main.District 5的案例陈述。

这是我到目前为止所做的:

CASE 
    WHEN Pubworks.dbo.csc.DistID = 1 THEN 
    'MAINT. DISTRICT 1' 
    WHEN Pubworks.dbo.csc.DistID = 2 THEN 
    'MAINT. DISTRICT 2' 
     ......
    WHEN Pubworks.dbo.csc.DistID = 5 THEN 
    'MAINT. DISTRICT 5' 
    ELSE    
    Pubworks.dbo.csc.DistID
    end
    as District

如何将varchar值转换为数据类型int? 先感谢您!

1 个答案:

答案 0 :(得分:2)

使用CASE表达式,所有值必须属于同一类型。您收到错误是因为您将两种类型混合为可能的结果:INTVARCHAR

假设DistIDINT,您可以执行以下操作:

Case    
    When Pubworks.dbo.csc.DistID In (1, 2, 3, 4, 5) 
        Then Concat('MAINT. DISTRICT ', Pubworks.dbo.csc.DistID)
    Else
        Convert(Varchar, Pubworks.dbo.csc.DistID)
End As District

假设它是VARCHAR,您可以改为:

Case    
    When Pubworks.dbo.csc.DistID In ('1', '2', '3', '4', '5') 
        Then Concat('MAINT. DISTRICT ', Pubworks.dbo.csc.DistID)
    Else
        Pubworks.dbo.csc.DistID
End As District