Click here to Skip to main content
15,908,175 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
what is the SQL query to prevent duplicate insertion of data in a data base table
Posted

Hi ,
You can use EXISTS Check this link MSDN[^]
Example [^]
Best Regards
M.Mitwalli
 
Share this answer
 
I would recommend you have a primary key (or setup a unique constraint) in your table.
This would prevent duplicate entry.

How to apply UNIQUE constraints to existing SQL columns[^] might help you get started.
 
Share this answer
 
Since you did not
1) State type of SQL (MySQL, Oracle, SQL Server....)
2) Give example of what you have tried
I will give you a hint for SQL Server. Look at LEFT JOIN
SQL
INSERT INTO Table2 (variable list)
SELECT variable list 
FROM Table1 
LEFT JOIN Table2 
ON Table1.keyfield = Table2.keyfield 
WHERE Table2.keyfield IS NULL;
 
Share this answer
 
create Proc Demo

SQL
@Empid int ,
@Name nvarchar(50),
@Phone nvarchar (50)
As
if not exist (select * from EMP where Empid=@Empid)
Begin
insert into EMP(Empid,Name,Phone) values (@Empid,@Name,@Phone)
End
 
Share this answer
 
v2
Comments
payal srivastava 3-Mar-22 7:20am    
it should be
if not exists(select *from EMP where Empid=@Empid)
sp ---

declare a var A

select count(*) into A from table where id=@id
if(A>0)
//insert
else
//update

end if
 
Share this answer
 

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