用SQL Server中的数字替换单词

时间:2014-07-07 08:21:11

标签: sql sql-server tsql sqldatatypes

我有一个包含一个单词的12列的表,我想将其更改为数字。例如:这12列中的每一列都可以具有5个预先指定的可能值之一:

  • highly agree
  • agree
  • no opinion
  • disagree
  • highly disagree

我想用数字更改这些单词,问题是数据类型,它不允许我将nvarchar数据类型更改为数字,我甚至尝试将text数据类型包含在内{非常同意,同意,没有意见,不同意,非常不同意}然后将它们更改为数字但是出现了这个错误:

  

Msg 402,Level 16,State 1,Line 1
  数据类型text和varchar在等于运算符中不兼容。

我使用的查询是:

[A1]= (case when [A1]='highly agree' then 1 
            when [A1]='agree' then 4 
            when [a1]='نظری ندارم' then 9 
            when [a1]='موافقم' then 16 
            when [a1]='کاملا موافقم' then 25 
            else [A1] end )

2 个答案:

答案 0 :(得分:1)

您不需要将列转换为文本数据类型,但必须在case语句中将数字用作varchar。您不能在case语句中混淆数据类型

[A1]= (case when [A1]='highly agree' then '1' when [A1]='agree' then '4' when     [a1]='نظری ندارم' then '9' when [a1]='موافقم' then '16' when [a1]='کاملا موافقم' then '25' else [A1] end )

除了你的问题,如果你想在这个字段上保持计算,那么你必须将整个列转换为Number。例如,您可以使用此查询

[CalculatedColumn]= CAST(case when [A1]='highly agree' then '1' 
                          when [A1]='agree' then '4' 
                          when [a1]='نظری ندارم' then '9' 
                          when [a1]='موافقم' then '16' 
                          when [a1]='کاملا موافقم' then '25' 
                          else '999' end ) AS INT) -- Any other number which can cast to integer

答案 1 :(得分:1)

试试这个:

 SELECT (CASE A1 WHEN 'highly agree' THEN '1'
                 WHEN 'agree' THEN '4' 
                 WHEN 'نظری ندارم' THEN '9' 
                 WHEN 'موافقم' THEN '16' 
                 WHEN 'کاملا موافقم' THEN '25' 
                 ELSE A1
         END) AS A1
相关问题