Click here to Skip to main content
15,867,835 members
Please Sign up or sign in to vote.
1.33/5 (2 votes)
See more:
I am trying to insert data if it does not exist in the database. and its not working.

Can anyone tell me why? Thanks in advance

SQL
insert into otlike values ("1452","g","g","df","dfg","fg","2014-09-16","dfg") Select id, workdate From  otlike Where not exists (select * from otlike where id= "1452"  and workdate = "2014-09-16")
Posted
Updated 29-Sep-14 16:24pm
v2

try this


SQL
IF not exists (select * from otlike where id= "1452"  and workdate = "2014-09-16")
BEGIN
   insert into otlike values ("1452","g","g","df","dfg","fg","2014-09-16","dfg")
END


good luck ;-)
 
Share this answer
 
Comments
NekoNao 25-Sep-14 21:48pm    
thanks! will try this.
Just check the below it is consisting of the same type of problem you are facing.

http://stackoverflow.com/questions/3164505/mysql-insert-record-if-not-exists-in-table[^]

Hope it helps.
 
Share this answer
 
you can achive by this two ways

If not Exists Method (Simple And Recomented way)

SQL
IF not exists (select * from otlike where id= "1452"  and workdate = "2014-09-16")
BEGIN
   insert into otlike values ("1452","g","g","df","dfg","fg","2014-09-16","dfg")
END


Using Tepm Variables
Declare @Count int
Set @Count = select count (*) from otlike where id= "1452"  and workdate = "2014-09-16"
if( @Count = 0 )
insert into otlike values ("1452","g","g","df","dfg","fg","2014-09-16","dfg")
begin
end
 
Share this answer
 
Comments
NekoNao 25-Sep-14 21:48pm    
thanks! will try this.
NekoNao 25-Sep-14 22:14pm    
did not work on mysql :(
Try this:
SQL
INSERT INTO otlike 
    SELECT '1452', 'g', 'g', 'df', 'dfg', 'fg', '2014-09-16', 'dfg' 
    WHERE NOT EXISTS(SELECT 1 FROM otlike WHERE id= '1452' AND workdate = '2014-09-16')
 
Share this answer
 
v2
Comments
NekoNao 25-Sep-14 21:48pm    
thanks! will try this.
Oshtri Deka 26-Sep-14 4:21am    
In your original post you haven't mentioned that you use MySQL.
I am not clairvoyant!


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

  Print Answers RSS


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