Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

Return Null If A Value Is A Certain Value

From Wiki

Jump to: navigation, search

You need to return NULL only if the value of your data is a certain value. How do you do this? There are three different ways.

NULLIF

  1. DECLARE @1 CHAR(1)
  2.     SELECT @1 ='D'
  3.  
  4.  
  5.     SELECT NULLIF(@1,'D')


REPLACE This should not really be used, I just added it here to demonstrate that you can in fact use it.

  1. DECLARE @1 CHAR(1)
  2.     SELECT @1 ='D'
  3.  
  4.     SELECT REPLACE(@1,'D',NULL)


CASE With case you can test for a range of values. You can test for example for values between A and D. If you reverse the logic then you also don't need to provide the ELSE part since it defaults to NULL anyway.

  1. DECLARE @1 CHAR(1)
  2.     SELECT @1 ='D'
  3.  
  4.  
  5.     SELECT CASE @1 WHEN 'D' THEN NULL ELSE @1 END
  6.  
  7.     --No else needed
  8.     SELECT CASE WHEN @1 <> 'D' THEN @1 END


And this is how you test for a range.

  1. --Null
  2.     DECLARE @1 CHAR(1)
  3.     SELECT @1 ='D'
  4.  
  5.     SELECT CASE WHEN  @1 BETWEEN 'A' AND 'D' THEN NULL ELSE @1 END


  1. --E
  2.     DECLARE @1 CHAR(1)
  3.     SELECT @1 ='E'
  4.  
  5.     SELECT CASE WHEN  @1 BETWEEN 'A' AND 'D' THEN NULL ELSE @1 END


Contributed by: --SQLDenis 16:34, 30 May 2008 (GMT)

Part of SQL Server Programming Hacks

Section NULLS

117 Rating: 1.7/5 (3 votes cast)