CASE语句使用IS NULL和IS NOT NULL

时间:2017-01-27 16:44:06

标签: sql sql-server null case

我正在构建一个新的SQL表,我在使用CASE语句时遇到了一些麻烦,我似乎无法理解。

我在WHEN参数中有两个不同的子句,用AND子句分隔。 这两个子句都在寻找NULL值,无论是null还是非null,以及它的变体。

      ,CASE WHEN [FULL_TELEPHONE_NUMBER] IS NOT NULL AND [EMAIL] IS NOT NULL THEN 'Phone Number AND Email Address Available'
        WHEN [FULL_TELEPHONE_NUMBER] IS NOT NULL AND [EMAIL] IS NULL THEN 'Phone Number ONLY Available'
        WHEN [FULL_TELEPHONE_NUMBER] IS NULL AND [EMAIL] IS NOT NULL THEN 'Email Address ONLY Available'
        WHEN [FULL_TELEPHONE_NUMBER] IS NULL AND [EMAIL] IS NULL THEN 'No Contact Details Available'
    ELSE 'ERROR' END AS '[CONTACT DETAILS AVAILABLE]'

不幸的是,数据只返回每个结果的第一个条件,关于查询列包含的内容。

虽然列中保存的数据显示为空,但是它们是否有可能不是真正的NULL?或者这里的NULL是正确的术语,我可以使用更好的东西吗?

非常感谢。

3 个答案:

答案 0 :(得分:1)

很可能数据实际上是空字符串而不是空字符串。您可以使用以下内容来覆盖:

WHEN IsNull([FULL_TELEPHONE_NUMBER], '') <> '' AND isnull([EMAIL], '') <> '' THEN 'Phone Number AND Email Address Available'

答案 1 :(得分:1)

这是解决这个问题的另一种方法。你可以使用&gt; &#39;&#39;而不是所有那些IS NULL等。

'ActiveSheet.DrawingObjects.Delete ' optional to delete all shapes when testing
Dim c As Range, cb As CheckBox

For Each c In Selection
    Set cb = c.Worksheet.CheckBoxes.Add(c.Left + c.Width / 2 - 8.25, _
            c.Top + c.Height / 2 - 8.25, 0, 0)  ' 8.25 is cb.Height / 2
    cb.Text = vbNullString                      ' to clear Caption
    cb.LinkedCell = c.Address(0, 0)             ' Example A1 instead of $A$1
    cb.Name = "cb" & cb.LinkedCell              ' optional
Next

Selection.NumberFormat = ";;;" ' optional to hide the cell values
Selection = True ' optional to check all at once (or 'selection = [#N/A]' for all xlMixed)

答案 2 :(得分:0)

当第一个参数的值等于第二个参数时,您可以使用nullif(col,'')返回null

,CASE 
  WHEN nullif([FULL_TELEPHONE_NUMBER],'') IS NOT NULL AND nullif([EMAIL],'') IS NOT NULL 
    THEN 'Phone Number AND Email Address Available'
  WHEN nullif([FULL_TELEPHONE_NUMBER],'') IS NOT NULL AND nullif([EMAIL],'') IS NULL 
    THEN 'Phone Number ONLY Available'
  WHEN nullif([FULL_TELEPHONE_NUMBER],'') IS NULL AND nullif([EMAIL],'') IS NOT NULL 
    THEN 'Email Address ONLY Available'
  WHEN nullif([FULL_TELEPHONE_NUMBER],'') IS NULL AND nullif([EMAIL],'') IS NULL 
    THEN 'No Contact Details Available'
    ELSE 'ERROR' 
    END 
    AS '[CONTACT DETAILS AVAILABLE]'

也可以简化为:

, [contact details available] = case 
    when nullif([full_telephone_number],'') is not null 
     and nullif([email],'') is not null 
      then 'phone number and email address available'
    when nullif([full_telephone_number],'') is not null 
      then 'phone number only available'
    when nullif([email],'') is not null 
      then 'email address only available'
      else 'no contact details available'
      end