Select Not Working中的Case语句



这是针对SQL Server 2012数据库的。。。

我正在从表中读取varchar数据列,根据用户选择的选项,数据可以是字母数字或数字。我需要按这个列排序,所以我试图使用case语句,但它似乎不起作用。下面是我正在做的事情的一个简化示例,但正如你所看到的,在这两种情况下,它都进入了案例陈述的Else。。。你知道我做错了什么吗?

Select  '1st Grade Math' topic Into #temp
Declare @rptView int
Set @rptView = 1
Select  Case @rptView 
      When 1 Then topic 
      Else cast(topic as int)
    End 
From    #temp 
Order by Case @rptView 
      When 1 Then topic 
      Else cast(topic as int)
     End 
Select  Case 
      When @rptView = 1 Then topic 
      Else cast(topic as int)
    End 
From    #temp 
Order by Case @rptView 
      When 1 Then topic 
      Else cast(topic as int)
     End 
drop table #temp 

根据您的表考虑以下示例:

 Select Case 1 When 1 Then topic 
                      Else 5
               End 
   From #temp 

失败,并出现以下错误:

Conversion failed when converting the varchar value '1st Grade Math' to data type int.

为什么?因为每个表达式都必须具有定义良好的数据类型。SQL Server推断第一列的类型是int,因为ELSE子句包含int。因此,它也尝试将topic转换为int,但失败了。

换句话说:你不能那样做。结果集中的字段可以是varcharint,而不是两者都是。

添加更多可能有所帮助的示例。。

declare @a int=1
declare @b varchar='b'
--this works
select 
case when @a=1 then @a else @b end
--this also works
select 
case when @a=2 then @b  else @b end

--this fails
select 
case when @a=1 then @b else @a end
--this fails
select 
case when @a=2 then @a else @b end

为什么。。?由于数据类型的优先级,SQL试图将所有内容转换为具有更高优先级的类型

最新更新