如何检查选择查询中的列中的值

时间:2016-05-02 07:37:03

标签: sql sql-server

我需要检查列中间名是否包含任何值。 如果它是空的,那么它不应该与名称连接。

    Select
     ..
     Agent,
     FirstName + ' ' MiddleName + ' ' + LastName as Name,
     ...
     from tbSystemUser 

在上面的查询中,如果MiddleName为空,则会在Name中添加两次空格。

6 个答案:

答案 0 :(得分:3)

您可以在CASE expression中使用COALESCE

 select
 ..
 Agent,
 case when coalesce(MiddleName, '') = '' then FirstName + ' ' + LastName 
      else FirstName + ' ' + MiddleName + ' ' + LastName 
 end as Name,
 ...
 from tbSystemUser 

答案 1 :(得分:1)

您可以使用案例陈述

Select
     ..
     Agent,
     Case MiddleName
     when ' ' then
     FirstName + ' ' + LastName 
     else
     FirstName + ' ' MiddleName + ' ' + LastName
     end
     as Name,
     ...
     from tbSystemUser 

OR

Select
         ..
         Agent,
         Case 
         when MiddleName = ' ' then
         FirstName + ' ' + LastName 
         else
         FirstName + ' ' MiddleName + ' ' + LastName
         end
         as Name,
         ...
         from tbSystemUser 

答案 2 :(得分:1)

Select
 ..
 Agent,
 FirstName + CASE WHEN MiddleName is not null THEN  ' ' + MiddleName else '' END  + ' ' + LastName as Name,
 ...
 from tbSystemUser 

答案 3 :(得分:1)

如果MiddleName不为null,则使用case表达式仅添加MiddleName + ' '部分:

Select
     ...
     Agent,
     FirstName +
     case when MiddleName is not null then MiddleName + ' ' end +
     LastName as Name,
     ...
     from tbSystemUser 

答案 4 :(得分:1)

我相信你可以这样使用子查询:

 Select Agent, Name from
 (
     Select t1.Agent as Agent, t1.FirstName + ' ' t1.MiddleName + ' ' + t1.LastName as Name,
     from tbSystemUser as t1 WHERE t1.MiddleName IS NOT NULL
 )
 NATURAL JOIN 
 (
      Select t2.Agent as Agent, t2.FirstName + ' ' + t2.LastName as Name,
      from tbSystemUser as t2 WHERE t2.MiddleName IS NULL
 )

这将根据两个选择创建的名称构建您的答案。

答案 5 :(得分:0)

SELECT FirstName 
   +IIF(ISNULL(LTRIM(RTRIM(MiddleName)),'')<>'',' '+MiddleName,'')
   +' '+LastName as Name

或者,如果您的SQL Server版本早于2012年:

SELECT FirstName 
   +CASE WHEN ISNULL(LTRIM(RTRIM(MiddleName))) <> '' 
      THEN ' '+MiddleName
      ELSE '' END
   +' '+LastName as Name

你没有指明空的意思。与此处的大多数其他解决方案不同,这将处理任何长度的空字符串,包括空值,但不处理特殊字符。我会假设没人去,并添加换行符作为中间名? :)