Click here to Skip to main content
15,883,883 members
Articles / Database Development / SQL Server
Tip/Trick

Using one Isnull() function to remove all null values from all columns a table in SQL Server

Rate me:
Please Sign up or sign in to vote.
2.33/5 (3 votes)
14 Nov 2012CPOL 47.1K   5   2
Write a sql query in which we use only one IsNull() function and it will remove all Null values(if any) from entire result set(from all rows)

Let's consider that we have a table that has several number of columns and they might have null values. Now we need to get blank or zero or anything else (whatever) in place of null values in the result set. For example let's have table (TEST) with data like: 

COL1

COL2

COL3

NULL

Kapil

NULL

TEST

NULL

NULL

And when we need a result like:

COL1

COL2

COL3 

A

Kapil

A

TEST

A

A

The SQL query would be-

SQL
Select IsNull(Col1,'A')as Col1, IsNull(Col2,'A')as Col2, IsNull(Col3,'A') as Col3 From TEST

But here we use three Isnull functions in the above query. But you have to write a SQL query (in SQL Server 2005 or above) in which there should be used only one ISNULL function (to avoid null values). And even query will be optimized if there will be less or no use of loop.

A solution will be like:

SQL
Declare @ColName as Varchar(400)
SEt @ColName=''
SELECT  @ColName= COALESCE( @ColName + ' ISNULL(' +c.name + ',''a'') ','', '') +
c.name + ', ' 
FROM sysobjects o
JOIN syscolumns c ON o.id = c.id
WHERE o.xtype = 'U'
AND (o.name ='NULLDEMO')
SEt @ColName=  ( 'Select ' + SUBSTRING(@ColName,0,LEN(@ColName)-1) + ' FROM NULLDEMO ')
EXEC(@ColName)

Here, we getting all column names of the table using the sysobjects table then we create a SQL string (I did not use any loop) and then we create a query ...And execute it using EXEC.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Tech Mahindra
India India
Working in Tech mahindra, Noida, India. Having more than 7 years knowledge in asp, ASP.net,C#, VB 6.0, VB.Net, XSLT, XML, RDLC report, Crystal Report, SQL Server, MySql, DB2 etc.

Comments and Discussions

 
GeneralMy vote of 1 Pin
John B Oliver13-Dec-12 9:42
John B Oliver13-Dec-12 9:42 
GeneralMy vote of 3 Pin
Spiff Dog15-Nov-12 7:43
Spiff Dog15-Nov-12 7:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.