2013-08-01 52 views
0

我在SQL Server 2012中遇到了问题。我遇到的问题是,当我在查询中尝试运行case语句时,case语句之前的列变得无法识别。使用SQL命令时遇到问题

我已经分离的问题,并发现这是块:

Select 
    [Address 1] + 
    Case 
     when [Address 2] = '' then ',' + [Address 2] 
     else '' end 
    Case 
     when Town <> '' then ',' + rtrim(Town) 
     else '' end 
    Case when County&lt;&gt;'' 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&lt;&gt;'' 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] 
+6

格式化您的查询将是一个好主意。 –

+0

就像我说的...我仍在学习。不过谢谢你的建议。 – GeoffWilson

回答

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 
+0

非常感谢...解决了我的问题 – GeoffWilson

+1

查看编辑后的版本。每个Case语句末尾都没有加号。 –

+0

谢谢你展示它是如何完成的。现在我可以使用它,当我再次需要它=]。 – GeoffWilson