Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

insert into when not exist in table

0 views
Skip to first unread message

Jonathan

unread,
Nov 19, 2009, 6:22:06 PM11/19/09
to
Hi using sql 2005. I want to insert into table A values(x,y) from table b.
However only when values x,y do not exist in table A?

I'm sure that this is really simply... I'm timing out when alternating
between <ahhh> brain freeze </ahhh> and <ahhh> max complicated </ahhh>

Many thanks,
Jonathan


Plamen Ratchev

unread,
Nov 19, 2009, 6:33:56 PM11/19/09
to
INSERT INTO A (x, y)
SELECT x, y FROM B
EXCEPT
SELECT x, y FROM A;


or


INSERT INTO A (x, y)
SELECT x, y
FROM B
WHERE NOT EXISTS(SELECT *
FROM A
WHERE A.x = B.x
AND A.y = B.y);

--
Plamen Ratchev
http://www.SQLStudio.com

--CELKO--

unread,
Nov 19, 2009, 6:51:51 PM11/19/09
to
>> I want to insert into table A values(x,y) from table b. However only when values x,y do not exist in table A?<<

Is here a UNIQUE (x, y) on table A? Then it will not happen. Think
constraints before code!!

Jeroen Mostert

unread,
Nov 20, 2009, 2:56:04 AM11/20/09
to

The UNIQUE guarantees no bad thing will happen. You'll still need a query to
ensure good things happen, though.

--
J.

0 new messages