sql - Unsure why this query is inserting duplicate records -
i have table customers has pk customerid , 2 date fields transdate , updateddate.
i have table paymentplan has 3 date fields: startdate, enddate , updateddate.
i need find customer records meet following criteria , insert them table.
transdatenotnull, falls between 1paymentplanrecord'sstartdate,enddate.transdatenull,updatedonfalls between 1paymentplanrecord'sstartdate,enddate.regardless of whether or not
transdatenull,updatedonvalue ofcustomersmust olderupdatedonofpaymentplan.
the problem i'm having query returning duplicate customerid values.
this procedure:
create procedure usp_find_customers_for_recalc @adaysback int begin set nocount on; set @adaysback = @adaysback * -1; -- since we're looking "back" in time, want negative value of number passed procedure insert recalc (customerid, insertedon, recordstatus, processedon) select customerid, getdate() insertedon, 0 recordstatus, null processedon customers inner join (select p.code, p.startdate, p.enddate, p.updatedon paymentplan p p.updatedon >= dateadd(day, @adaysback, getdate()) , deletedon null group p.code, p.startdate, p.enddate, p.updatedon) pinfo on customers.code = pinfo.code (isnull(customers.transdate, customers.updatedon) >= pinfo.startdate , isnull(customers.transdate, customers.updatedon) <= pinfo.enddate , customers.updatedon < pinfo.updatedon) , customers.deletedon null end if run above procedure, run following commands:
select count(distinct(customerid)) recalc select count(customerid)) recalc the second result approximately twice big first result.
i cannot determine wrong query resulting in many duplicate customers being added when not need recalculated.
the duplicates caused data in paymentplan table. although intention periods defined in table non-overlapping given code, not case, , explain duplicates.
to identify if indeed have such overlapping periods in paymentplan table, issue statement:
select p1.code, p1.startdate paymentplan p1 inner join paymentplan p2 on p1.code = p2.code , p1.startdate between p2.startdate , p2.enddate if query returns records, explains duplicates. returned records give clue such inconsistencies in paymentplan table.
once have resolved those, no longer produce duplicates.
Comments
Post a Comment