如何在sql server中为此查询分配列标题/名称?

时间:2017-01-10 06:46:33

标签: sql sql-server sql-server-2012

这是我的简单查询。

Declare @custName INT 
Set @custName = 2 
Select  case @custName 
when 1 then 'abc' 
when 2 then 'xyz'
when 3 then 'pqr'
end

上面的查询运行正常。

输出

SQL Statement

我正在考虑将列或标题名称指定为客户名称。

我尝试了查询的一些排列。

  • Declare @custName INT Set @custName = 2 Select case @custName as CustomerName when 1 then 'abc' when 2 then 'xyz' when 3 then 'pqr' end
  • Declare @custName INT Set @custName = 2 Select CustomerName as case @custName when 1 then 'abc' when 2 then 'xyz' when 3 then 'pqr' end

但是返回错误。

  

所以我的问题是如何分配一些合适的标题/列名?

3 个答案:

答案 0 :(得分:2)

您可以为结果列

指定别名
Declare @custName INT 

Set @custName = 2 

Select  case @custName 
 when 1 then 'abc' 
 when 2 then 'xyz'
 when 3 then 'pqr'
end as custname

答案 1 :(得分:1)

SQL Server中至少有3种方法可以执行此操作:

<expression> as <alias>
<expression> <alias>
<alias> = <expression> 

因此,对于您的示例,它可以是:

DECLARE @custName INT  
SET @custName = 2  
SELECT  CASE @custName
          WHEN 1 THEN 'abc'
          WHEN 2 THEN 'xyz'
          WHEN 3 THEN 'pqr'
        END AS CustomerName

或:

DECLARE @custName INT  
SET @custName = 2  
SELECT  CASE @custName
          WHEN 1 THEN 'abc'
          WHEN 2 THEN 'xyz'
          WHEN 3 THEN 'pqr'
        END CustomerName

或:

DECLARE @custName INT  
SET @custName = 2  
SELECT  CustomerName = CASE @custName
          WHEN 1 THEN 'abc'
          WHEN 2 THEN 'xyz'
          WHEN 3 THEN 'pqr'
        END 

答案 2 :(得分:0)

您需要使用Alias Name并使用方括号来转义别名中的空格。在使用SQL SERVER 2012

Choose中,有一种简单的方法可以做到这一点
Declare @custName INT 

Set @custName = 2 

Select  Choose(@custName,'abc', 'xyz', 'pqr') as [Customer Name]