Friday, May 14, 2010

COALESCE and ISNULL functions

Both of these functions are similar which allow you to replace a null value of column with any expression belong to the same data type of this column except in one point, COALESCE has ability in case you need to pass a list of expressions to be replaced when the value comes NULL.

Let's see these examples:
DECLARE @Table Table
        (Col1 VARCHAR(10) NULL ,
         Col2 INT NULL,
         Col3 INT NULL)

INSERT INTO @Table
SELECT  'Microsoft',1,100 UNION ALL
SELECT  NULL,2,200        UNION ALL
SELECT  NULL,NULL,300     UNION ALL
SELECT  NULL,NULL,NULL 

--Both Functions are similar In Case of One Expression 
SELECT Col1 , ISNULL(Col1,'No Value') AS [Col1 with ISNULL] 
FROM @Table
SELECT Col1 , COALESCE(Col1,'No Value') AS [Col1 with COALESCE] 
FROM @Table

--COALESCE allows you to pass a list of expressions.
--When first Expression (in this case Col2 ) is null then 
--it will take the next expression (in this case Col3) and 
--replaced with Null value and so on.
SELECT Col1 , COALESCE(Col1,CAST(Col2 AS VARCHAR(10)),
                            CAST(Col3 AS VARCHAR(10))) AS [List of expressions wiht COALESCE] FROM @Table


No comments: