March 20, 2008

Display Non-Null Values Even If A Column Contains Null




Our tables can contain NULL values if the columns allows them. However while displaying the data to the customers, we often have to display non-null values even if a column contains null. Let us see how to do that :

-- CREATE SAMPLE TABLE

CREATE TABLE #Customers (id integer, cname varchar(20), pincode int)

-- SAMPLE DATA

INSERT INTO #Customers VALUES (1, 'Jack',45454 )
INSERT INTO #Customers VALUES (2, 'Jill', 43453)
INSERT INTO #Customers VALUES (3, 'Tom', 43453)
INSERT INTO #Customers VALUES (4, 'Kathy', null)
INSERT INTO #Customers VALUES (5, 'David', 65443)
INSERT INTO #Customers VALUES (6, 'Kathy', null)
INSERT INTO #Customers VALUES (7, 'Kim', 65443)

-- QUERY TO DISPLAY NON-NULL Values

SELECT ID, cname, COALESCE(pincode,0) as pincode FROM #Customers

As you observe, COALESCE is used which returns the first nonnull expression among its arguments. So if the pincode is null, it returns the first nonnull expression, i.e 0.


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

0 Responses to "Display Non-Null Values Even If A Column Contains Null"
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions