SQLUSA

Microsoft SQL Server 2005 Best Practices

Microsoft SQL Server 2000 Best Practices

How to use the COALESCE function?

 

The COALESCE(expression1,...n) is equivalent to this CASE function:

CASE
WHEN (expression1 IS NOT NULL) THEN expression1
...
WHEN (expressionN IS NOT NULL) THEN expressionN
ELSE NULL

It returns the first non-NULL expression from the list.

An example for usage returns the annual compensation for hourly, salaried and commission workers. Only one column is populated, the other 2 are nulls for each employee.

SELECT CAST(COALESCE(HourlyWage * 40 * 52,
AnnualSalary,
Commission * Sales)
AS smallmoney) AS 'Total Compensation'
FROM Salary

 

 

Best in the World in SQL Server Training
 
SQLUSA.com Home Page