Everyone may have encountered this duplicate records in the table scenario.
I have a table where i save the patient name,age,sex and his demographic details.If these patient details got saved more than once(Reasons for saving more than once can be many for ex::business logic code in the programming language etc)
CREATE OR REPLACE FUNCTION fncount111()
RETURNS INTEGER AS
$BODY$
declare
drug1 record;
//record is a datatype in postgres //
//when the function gets called
the row that needs to be checked with the next all rows is kept in the drug1
For ex:after the first row is checked with the next all rows in the table then second row
is kept in the drug1//
drug2 record;
//Here searching for a duplicate record is limited to 3 rows in a table
i.e; if drug1 consists row1 then row2, row3,row4 are inserted into this drug2
and checked//(I have limited it to three rows u can limit it to any number of rows you want// )
checking record;
checking2 record;
patientcount integer;
//After each row is added to drug1 for searching the count
is incremented by one this count is used in inserting
the records into drug2 and comparing//
patientcount1 integer;
begin
patientcount=0;
patientcount1=0;
--raise info '%',;
//inserting the record to be checjed into drug1//
for drug1 in (
select * from mr_regisration_header ORDER BY mr_regh_id desc )
loop
checking=drug1;
//incrementing the count i.e., for row1 patientcount=1, when row2 gets inserted pateintcount=2//
patientcount=patientcount+1;
//If row 1 is insert into drug1 then row2,row3,row4 to be inserted into drug2 for checking(because in query my limit is 3)//
//offset patientcount clause--If row2(for row2 patient count wil be 2) is there in drug1
for comparison then row3,row4,row5 are to be compared with row2
so i am leaving two rows i.e,offset patientcount(offset 2) //
//for loop is for checking row2 with row3,row2 with row4,row2 with row5//
for drug2 in(select * from mr_regisration_header offset patientcount limit 3)
loop
checking2=drug2;
//checking criteria if firstname,cliniccode,date are equal then patient count1 will be incremented by one //
if(checking.mr_regh_first_name=checking2.mr_regh_first_name AND checking.mr_regh_inst_code=checking2.mr_regh_inst_code and checking.mr_regh_registration_date=checking2.mr_regh_registration_date)
THEN
raise info 'hai %',drug2.mr_regh_first_name;
patientcount1=patientcount1+1;
END IF;
end loop;
end loop;
RETURN patientcount1;
end;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;
ALTER FUNCTION fncount111() OWNER TO postgres;
No comments:
Post a Comment