Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

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: 2.1/5 (8 votes cast)