I need to do the 2nd part of this question(https://i.sstatic.net/iubZR.jpg) with a cursor but my code is updating every rows with the same value. Basically i need to check if the timein and timeout is in a certain range like between 9am and 12pm the payment will be 350. Also if its from, lets say 10am to 16pm, i need to calculate between 2 ranges.
I tried the code below but its not working. Its expected to go through the timein and timeout and calculate the amount to be paid into amtpaid column.
create table babysitter (
babysitterid char(5) not null primary key,
datein date not null,
timein time not null,
dateout date not null,
timeout time not null,
noofhrswrk int,
amtpaid int
);
insert into babysitter values('BS001', '18-Jan-2019', '10:00', '18-Jan-
2019', '16:00', '', '')
insert into babysitter values('BS002', '15-Jan-2019', '13:00', '15-Jan-
2019',
'20:00', '', '')
insert into babysitter values('BS003', '21-Jan-2019', '21:00', '21-Jan-
2019',
'07:00', '', '')
insert into babysitter values('BS004', '11-Jan-2019', '08:00', '11-Jan-
2019', '13:00', '', '')
declare @timein time
declare @timeout time
declare @hoursworked datetime
declare Calculate_No_Hrs cursor for
select timein, timeout, noofhrswrk from babysitter
open Calculate_No_Hrs
fetch next from Calculate_No_Hrs into @timein, @timeout, @hoursworked
while (@@FETCH_STATUS = 0)
begin
update babysitter
set noofhrswrk = abs(datediff(hour, timeout, timein))
fetch next from Calculate_No_Hrs into @timein, @timeout, @hoursworked
end
close Calculate_No_Hrs
deallocate Calculate_No_Hrs ---end first question
--------------------------------------------------------------
declare @timein time
declare @timeout time
declare @amount int
declare @hourswrk int
declare @pay int
set @pay = 0
declare Amt_Paid cursor for
select timein, timeout, noofhrswrk, amtpaid
from babysitter
open Amt_Paid
fetch next from Amt_Paid into @timein, @timeout, @hourswrk, @amount
while (@@FETCH_STATUS = 0)
begin
if (@timein >= '09:00' and @timeout <= '12:00')
begin
set @amount = 350 * @hourswrk
set @pay += @amount
-- update babysitter
-- set amtpaid = @amount
end
if (@timein >= '12:00' and @timeout <= '17:00')
begin
set @amount = 400 * @hourswrk
set @pay += @amount
-- update babysitter
-- set amtpaid = @amount
end
if (@timein >= '17:00' and @timeout <= '21:00')
begin
set @amount = 500 * @hourswrk
set @pay += @amount
-- update babysitter
-- set amtpaid = @amount
end
if (@timein >= '21:00' and @timeout <= '00:00')
begin
set @amount = 600 * @hourswrk
set @pay += @amount
-- update babysitter
-- set amtpaid = @amount
end
if (@timein >= '00:00' and @timeout <= '07:00')
begin
set @amount = 800 * @hourswrk
-- update babysitter
-- set amtpaid = @amount
end
update babysitter
set amtpaid = @pay
fetch next from Amt_Paid into @timein, @timeout, @hourswrk, @amount
end
close Amt_Paid
deallocate Amt_Paid
babysiteridin theupdatestatement.noofhrswrk