0

I am having trouble with a command in SQL Server 2012. The problem i am having is that when i try and run a case statement within a query the columns before the case statement then become unrecognized.

I have isolated the problem and found it to be this block:

  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

Any help would be great because i am still learning SQL.

Here is the full code block:

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]
4

1 回答 1

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
于 2013-08-01T12:36:54.710 回答