Wednesday, June 19, 2013

Cleaner code with SQL Coalesce

ver 1.

if @runDate != null
  set @rd = CONVERT(VARCHAR(10),@runDate,101)
else
  set @rd = CONVERT(VARCHAR(10),getdate(),101)

set @rd = replace(@rd,'/','')



ver 2.

set @rd = replace(CONVERT(VARCHAR(10),COALESCE(@runDate,getdate()),101),'/','')


Coalesce takes in a list of values,  it will return the first non null value.

I also wrapped the replace call around the results of the convert statement.


More on MSDN: COALESCE (Transact-SQL)

No comments: