0

I have the following query:

UPDATE FinanceTable
SET    PercentageComplete = (SELECT ( Sum(LabourFinance.HoursTaken / LabourFinance.Hours) / Count(LabourID) )
                             FROM   LabourFinance
                             WHERE  FinanceID = (SELECT TOP 1 FinanceID
                                                 FROM   FinanceTable
                                                 ORDER  BY changedate DESC)
                             GROUP  BY FinanceID)
WHERE  FinanceID = (SELECT TOP 1 FinanceID
                    FROM   FinanceTable 
                    ORDER  BY changedate DESC)

what this query does is select 1 specific cell based upon a changedate, and i am using that to update a cost value in my FinanceTable.

this scenario is causing me the issue:

  • I have allocated 100 hours to complete a task
  • HoursTaken is currently 0 after inserting into the table as ive not started yet
  • when calculating PercntageComplete, SQL Server will not let me do (0 / 100), therefore causing an error...

How can i prevent this? my desired outcome would be PercentageComplete = 0%

thanks for any input :) below is the error message i get by runnig the query above

enter image description here

Crezzer7
  • 2,265
  • 6
  • 32
  • 63

1 Answers1

2

Refer This

How to avoid the “divide by zero” error in SQL?

UPDATE FinanceTable
SET    PercentageComplete = (SELECT COALESCE (Sum(COALESCE (LabourFinance.HoursTaken / NULLIF(LabourFinance.Hours, 0), 0)) / NULLIF(Count(LabourID), 0), 0)
                             FROM   LabourFinance
                             WHERE  FinanceID = (SELECT TOP 1 FinanceID
                                                 FROM   FinanceTable
                                                 ORDER  BY changedate DESC)
                             GROUP  BY FinanceID)
WHERE  FinanceID = (SELECT TOP 1 FinanceID
                    FROM   FinanceTable
                    ORDER  BY changedate DESC) 
Community
  • 1
  • 1
Recursive
  • 954
  • 7
  • 12