Link to home
Start Free TrialLog in
Avatar of Jorhal
Jorhal

asked on

SQL insert value into table if does not already exist

For my database with two tables: Table1, Table2
There is a shared field:Column1

I need to create a SQL statement that checks every Column1 value in Table1.  If that value does not already exist in Column1 of Table2, then insert the value into Column1 of Table2.

Any assistance is appreciated.
Avatar of Ataraxia2010
Ataraxia2010

Try This:
Select @count=count(*) from table where condition......

if( @count>0)
Begin
Print 'match'
End

Else
Begin
print 'no match'
End
You simply right click on one of the application bars in the navigation pane and select open in new window, then drag the window to your other screen.

INSERT INTO Table2
SELECT * FROM Table1 WHERE Column1 NOT IN (SELECT Column1 FROM Table2)

I understood like - You need to insert those records into Table2, that present in Table1, but not in Table2
Raj


ASKER CERTIFIED SOLUTION
Avatar of Rajkumar Gs
Rajkumar Gs
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
INSERT INTO Table2 (Column1)
    SELECT t1.Column1
    FROM Table1 t1
    LEFT JOIN Table2 t2 ON t1.Column1 = t2.Column1
    WHERE t2.Column1 IS NULL

or if the key value in table 2 exists with a null field in column1 and you're trying to make 2 tables that look alike

    UPDATE Table2
    SET Column1 = t1.Column1
    FROM Table1 t1
    JOIN Table2 t2 ON t1.KeyValue = t2.KeyValue
    WHERE t2.Column1 IS NULL
Avatar of Parth Malhan
Please make sure that the 2 tables have the exactly same fields in the same order

try the following code:

insert into table2
select * from table1
inner join table 2 on table1.column1<>table2.column1