Click here to Skip to main content
15,884,838 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I write a query for insert records but some times it insert duplicate records
my query like this


DECLARE @cnt AS INT
SET @cnt=(SELECT COUNT(*) FROM
tbltest
WHERE
Empcode= @Uid AND
SID= @Sid AND
PID= @Pid AND
EmpID=@EmpId AND
RMID= @RMId AND
EndTime IS NULL)

IF @cnt=0
BEGIN
insert into tbltest (EmpCode,sid,Pid,Empid,RmId,Param1,Starttime,Transtype) values(
@Uid,
@Sid,
@Pid,
@EmpId,
@RMId,
@processname_param1,@CURRDATE,'Input')
END

i used code for avoiding duplication but some times it insert duplicate records.
Posted

Add a primary key to this table.
This primary key would be a combination of those columns that together define a unique field.

Even inf you don't want to define a primary key, you can define a unique constraint - Create Unique Constraints[^].
 
Share this answer
 
Comments
Dj@y 14-Jan-16 2:52am    
i already use primary key.
Abhinav S 14-Jan-16 2:57am    
Check the data you are passing. Something could be wrong with the count query.
Use a unique constraint on non-primary fields.
Dj@y 14-Jan-16 3:06am    
Boss i can't applay unique on non-primary fields, it avoid me to insert data for another user which have same field except EmpId
Try removing AND EndTime is NULL filter in your select query and check again

SQL
SET @cnt=(SELECT COUNT(*) FROM 
tbltest 
WHERE 
Empcode= @Uid AND 
SID= @Sid AND 
PID= @Pid AND 
EmpID=@EmpId AND 
RMID= @RMId) 
 
Share this answer
 
Comments
Dj@y 14-Jan-16 3:03am    
My all insertion is depend on EndTime only if EndTime is null then only i insert record.
_Asif_ 14-Jan-16 3:06am    
Can you share your rows that has been duplicated with the original one?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900