SQLTeam.com | Weblogs | Forums

If fieldA is Null then fieldA = GetDate()?


#1

I have the following query...
SELECT StartDate, EndDate, FROM table
I am trying to figure out how to add the following to the query,
if EndDate is NULL then replace the NULL with Todays Date

Also I want to create a new column I also want to create a new column that tells me the number of days between StartDate and EndDate.

I am brand new to SQL and just starting out writing TSQL statements. Thank you very much for the help.
Steve


#2
SELECT StartDate, 
	COALESCE(EndDate, GETDATE()), 
	DATEDIFF(dd, StartDate, COALESCE(EndDate, GETDATE()) ) AS diff
FROM table

If you don't want to see the time portion in GETDATE(), use CAST(GETDATE() as DATE) instead of just GETDATE()


#3

James, thank you very much that did exactly what I was looking for. Now I need to figure out why. :slight_smile: I'll look that up myself, but thank you.