组合列名称会导致错误

时间:2016-08-26 10:31:30

标签: sql sql-server sql-server-2005

我想要组合两个列并显示数据,我尝试如下

select 
    case 
       when status = 'R' 
          then 'Resign'
       when status = 'A' 
          then 'Active' 
    end as status1, 
    Program_name + ' ' + emp_card_no as program_details,
    * 
from 
    GetEmployeeDetails
where 
    emp_name = 'ABHAY ASHOK MANE'
    and STATUS = 'A' 
order by
    EMP_NAME

但是我收到了一个错误:

  

将数据类型varchar转换为数字时出错。

以下是可用的样本数据

img

5 个答案:

答案 0 :(得分:2)

试试这个:

select 
  case when status='R' then 'Resign'
       when status='A' then 'Active' 
  end as status1, 
  Program_name + ' (' + convert(varchar, emp_card_no) + ') ' as program_details,
* 
from GetEmployeeDetails
Where emp_name ='ABHAY ASHOK MANE'and STATUS= 'A' ORDER BY EMP_NAME

答案 1 :(得分:2)

如果您需要括号,请使用以下内容:

select 
  case when status='R' then 'Resign'
       when status='A' then 'Active' 
  end as status1, 
  Program_name + ' (' + convert(varchar(10), emp_card_no)+')' as program_details,
* 
from GetEmployeeDetails
Where emp_name ='ABHAY ASHOK MANE'and STATUS= 'A' ORDER BY EMP_NAME

答案 2 :(得分:2)

CAST Int value列到VARCHAR:

在您的查询中施放emp_card_no 到VARCHAR

select 
    case when status='R' then 'Resign'
    when status='A' then 'Active' end as status1, 
    [Program_name] + ' ' + CAST(emp_card_no AS VARCHAR(50)) as program_details,
* 
from GetEmployeeDetails
Where emp_name ='ABHAY ASHOK MANE'and STATUS= 'A' ORDER BY EMP_NAME

答案 3 :(得分:1)

你可以使用将在内部转换的concat ..

select case when status='R' then 'Resign'
when status='A' then 'Active' end as status1, 
 concat(Program_name, ' ', emp_card_no) as program_details,
* from GetEmployeeDetails
Where emp_name ='ABHAY ASHOK MANE'and STATUS= 'A' ORDER BY EMP_NAME

答案 4 :(得分:0)

可以对字符串类型值执行

列组合。因此,如果不是,则必须将列转换为varchar数据类型。

以下是案例陈述中的一项改进的解决方案。

select 
case status 
   when 'R' 
      then 'Resign'
   when 'A' 
      then 'Active' 
end as status1, 
Program_name + ' ' + convert(varchar(50),emp_card_no) as program_details,
* 
from 
GetEmployeeDetails
where 
emp_name = 'ABHAY ASHOK MANE'
and STATUS = 'A' 
order by
EMP_NAME