ISNULL等效于空字段

时间:2010-09-15 18:54:49

标签: sql sql-server-2005 coalesce isnull

是否存在类似ISNULL()或COALESCE()的内容,但不是检查空值而是检查空值。

例如:

  SELECT cu.last_name, cu.first_name, cu.email, hu.email FROM 
 (SELECT DISTINCT c.first_name, c.last_name, c.email, c.household_id, h.head_of_household_id
  FROM rd_customers c
  JOIN rd_households h ON c.household_id = h.household_id
  JOIN ad_registrations r ON r.customer_id = c.customer_id
  JOIN ad_meeting_times a ON  r.session_id = a.session_id and a.meeting_time_id = 203731) cu
  LEFT JOIN rd_customers hu ON hu.customer_id = cu.head_of_household_id

而不是返回四列我想要得到三个而第三个假设有cu.email或hu.email的值,如果第一个是EMPTY! ISNULL和COALESCE不在这里工作我不知道为什么

3 个答案:

答案 0 :(得分:8)

您可以随时使用案例:

select  case when cu.email is null or cu.email = '' then hu.email 
             else cu.email end as ColumnName
from    YourTable

答案 1 :(得分:3)

查看NULLIF (Transact-SQL)

  

NULLIF返回第一个表达式if   这两个表达方式并不相同。如果   表达式是相等的,NULLIF   返回类型为null的null值   第一个表达。

试试这个:

COALESCE(NULLIF(cu.email,''),NULLIF(hu.email,''))
如果cu.email和hu.email是空字符串或NULL

的任意组合,

将返回NULL

答案 2 :(得分:1)

这将捕获null或空cu.email并改为使用hu.email:

SELECT cu.last_name, 
       cu.first_name, 
       CASE WHEN ISNULL(cu.email, '') = '' THEN
            hu.email
       ELSE
            cu.email
       END AS email
FROM 
(
  SELECT DISTINCT c.first_name, 
                  c.last_name, 
                  c.email, 
                  c.household_id, 
                  h.head_of_household_id
  FROM rd_customers c
  JOIN rd_households h 
    ON c.household_id = h.household_id
  JOIN ad_registrations r 
    ON r.customer_id = c.customer_id
  JOIN ad_meeting_times a 
    ON  r.session_id = a.session_id 
      AND a.meeting_time_id = 203731
) cu
LEFT JOIN rd_customers hu 
  ON hu.customer_id = cu.head_of_household_id