The code below is used for a table with production tasks. It moves tasks to the next day where the sum of hours required for actions belonging to the same production order is more than 8. The code below works fine, though I was wondering whether the code itself could be written in a more efficient manner.while (select sum(a.hours)       from table1 a       join inserted i on i.productionorderid = a.productionorderid                       and i.productionorder_rowid = a.productionorder_rowid       where i.date = a.date         and i.hours is not null         and i.date is not null) > 8begin          update a    set a.date = case                     when exists (select dateadd(day,1,a.date)                                  from table 1 a                                 where a.productionorderid = i.productionorderid                                   and a.productionorder_rowid = i.productionorder_rowid                                   and a.productionorder_row_task_id= i.productionorder_row_task_id                                   and a.date is not null                                   and a.hours is not null)                       then dateadd(day, 1, a.date)                       else dateadd(day, 3, a.date)                 end    from table1 a    join inserted i on i.productionorderid = a.productionorderid                    and i.productionorder_rowid = a.productionorder_rowid    where         a.serialnumber = (select max(a.serialnumber) -- the highest serial number is moved to the next day                           from table1 a                          where a.productionorderid = i.productionorderid                            and a.productionorder_rowid = i.productionorder_rowid                            and a.date = i.date)    if (select sum(a.hours)        from table1 a        join inserted i on i.productionorderid = a.productionorderid                        and i.productionorder_rowid = a.productionorder_rowid) <= 8        break    else        continueend
Rescheduling long production tasks to the next day
sql;sql server;t sql