0

I'm using Microsoft SQL Server 2012 and keep running into the error

Divide by zero error encountered.

for the statement like below. I want to add a null if the two dates are the same.

SELECT 
    sf.TotalPrice / DATEDIFF(day, sf.StartDate,sf.EndDate) as DailyAllocatedRevenue,
    sf.TotalPrice
FROM 
    sftable 
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425

4 Answers4

2

Use NullIf Function in Sql-Server it Will return null if difference returns 0

See this link will help you

SELECT 

    sf.TotalPrice / NULLIF(DATEDIFF(day, sf.StartDate,sf.EndDate),0) as DailyAllocatedRevenue
    ,sf.TotalPrice

FROM sftable 
Community
  • 1
  • 1
2

You can just wrap the DATEDIFF in a NULLIF:

SELECT 

    sf.TotalPrice / NULLIF(DATEDIFF(day, sf.StartDate,sf.EndDate),0) as DailyAllocatedRevenue
    ,sf.TotalPrice

FROM sftable 

If any of the inputs are NULL, or the result is 0, it will become NULL and that propagates through the division.

Damien_The_Unbeliever
  • 227,877
  • 22
  • 326
  • 423
  • @Damien, not really sure the OP has read or understood your warning about NULL propagation! – Paul Bambury Aug 23 '16 at 10:24
  • @PaulBambury - I think the null propagation is actually a part of what they wanted. I could be wrong but I think they wanted the overall result (for `DailyAllocatedRevenue`) to be `NULL` rather than producing a divide by zero error. – Damien_The_Unbeliever Aug 23 '16 at 10:27
1

Try and use

case 
     when sd.startdate <> sd.EndDate then sf.TotalPrice / DATEDIFF(day, sf.StartDate, sf.EndDate) as DailyAllocatedRevenue
     else sf.TotalPrice
end
Paul Bambury
  • 1,212
  • 1
  • 12
  • 17
0
IIF(DATEDIFF(day, sf.StartDate,sf.EndDate)=0,NULL, sf.TotalPrice
/Convert(Decimal(18,4),DATEDIFF(day, sf.StartDate,sf.EndDate)))

Should do the trick

Szebeni
  • 66
  • 2