Click here to Skip to main content
15,885,141 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello friends

I have sql statement that executes without exception but the result is not correct.

I concontenated fname, mname and and sname to form full_name but when I run the script, records with null values return Null for the full_name even though fname and sname exist for those records.

Please find my script below:
SQL
select  emp_id, 
   CASE mname WHEN NULL THEN  emp_id + ' - ' + upper(sname) COLLATE DATABASE_DEFAULT   + ',  ' + fname + N''   
   ELSE 
      emp_id + ' - ' + upper(sname) COLLATE DATABASE_DEFAULT + ',  ' + fname + '  ' +  mname end as full_name
from emp


Thanks in advance for your assistance
Posted

Check up your logic and consider using COALESCE(mname, '') to replace null with empty string.
See also, for example: http://stackoverflow.com/questions/8233746/concatenate-with-null-values-in-sql[^] (presently, a top answer).

—SA
 
Share this answer
 
Comments
noblepaulaziz 10-Feb-15 17:06pm    
Thanks so much for solution
Sergey Alexandrovich Kryukov 10-Feb-15 17:28pm    
You are very welcome.
Good luck, call again.
—SA
Hi,

There are 2 ways to achieve the task.

1.) As mentioned in the solution by SA above using COALESCE(mname, '')
2.) Using ISNULL(mname, '') for example:
Select IsNull(ColName, '') As ColName From TableName



You can use any one of these methods to check for the null values in your script.

Thanks
Sisir Patro
 
Share this answer
 
Comments
deepakdynamite 10-Feb-15 6:56am    
using COALESCE(mname, '') is better than IsNull.
jaket-cp 10-Feb-15 10:01am    
Any examples on why coalesce is better than isnull?
deepakdynamite 10-Feb-15 22:34pm    
For Eg: ISNULL(mname,FName)
In this case if Fname is also null and you want to check it, you have to code like this:

ISNULL(mname,ISNULL(FName,'Deepak'))

Where as if you are using Coalesce, you can directly write as
COALESCE(MNAME,FNAME,'Deepak'). You can provide n number of columns.

There is one more point for which you need to execute following code and check the difference.

DECLARE @NAME varchar(3) = null

SELECT ISNULL(@Name,'Deepak')
Select COALESCE(@Name,'Deepak')
jaket-cp 11-Feb-15 4:05am    
Thanks for that.
So if multiple null checks are required then coalesce is the way to go.
Also done some reading up - isnull is not standard and coalesce is.

There is one down side, it is hard to spell :(
that gets me all the time :)
deepakdynamite 11-Feb-15 23:01pm    
Right!!!!
Enjoy :)

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900