我在使用SQL Server 2012中的命令时遇到问题。我遇到的问题是,当我尝试在查询中运行case语句时,case语句之前的列将变为无法识别。
我已经解决了这个问题并发现它是这个块:
Select
[Address 1] +
Case
when [Address 2] = '' then ',' + [Address 2]
else '' end
Case
when Town <> '' then ',' + rtrim(Town)
else '' end
Case when County<>'' then ','+rtrim(County) else '' end
) as Address
from Employees
任何帮助都会很棒,因为我还在学习SQL。
以下是完整的代码块:
Select
'Chorley' as [Site Address],
[EmpID] as EmployeeID,
[First Name],
[Surname],
Manager as [Manager directly over employee],
Email,
'' as WorkPhone,
[Home Tel],
[Mobile Tel],
(
[Address 1] +
Case when [Address 2] = '' then ',' + [Address 2] else '' end
Case when Town <> '' then ',' + rtrim(Town) else '' end
Case when County<>'' then ','+rtrim(County) else '' end) as Address,
Pcode,
[NI No],
DOB,
[Job Title],
[Start Date],
[Hours Worked],
[Days And Times] as DaysAndTimes,
Holidays,
'',
[Contract] as 'Contract'
from Employees
where [Employment Status]<>'Leaver'
Order By [Department], [SurName]
答案 0 :(得分:8)
您必须在案例之间使用+才能连接:
在
Select [Address 1]+
Case when [Address 2] = '' then ',' + [Address 2] else '' end
Case when Town <> '' then ',' + rtrim(Town) else '' end
Case when County<>'' then ','+rtrim(County) else '' end) as Address
from Employees
在
Select [Address 1]+
Case when [Address 2] = '' then ',' + [Address 2] else '' end +
Case when Town <> '' then ',' + rtrim(Town) else '' end +
Case when County<>'' then ','+rtrim(County) else '' end) as Address
from Employees