| |
|
If this is your first visit, be sure to check out the FAQ by clicking the link above.
You may have to register before you can post: click the register link above to proceed.
To start viewing messages, select the forum that you want to visit from the selection below.
|
 |

01-27-10, 12:49
|
|
Registered User
|
|
Join Date: Jun 2009
Posts: 6
|
|
|
MERGE alternative on DB2 8?
|
|
Hi,
I need a statement (to be used on simple scripts, not procedures) which will check if a value exists before inserting.
LIKE:
INSERT INTO names("id", "name")
VALUES
(1, 'Dave'),
(2, 'Thomas'),
(3, 'Paul'),
(4, 'Alex'),
(5, 'Patrick'),
(6, 'PJ')
IF NOT EXISTS (SELECT * FROM names);
How can I achieve that on DB2 8?
Cheers
|
|

01-27-10, 12:54
|
|
Registered User
|
|
Join Date: Jan 2003
Posts: 3,575
|
|
DB2 version 8 has a MERGE statement that will do that.
Andy
|
|

01-27-10, 13:30
|
|
:-)
|
|
Join Date: Jun 2003
Location: Toronto, Canada
Posts: 4,449
|
|
|
|
See if this works (I don't have a DB2 v8 instance handy to test it):
Code:
INSERT INTO names("id", "name")
select * from table (
VALUES
(1, 'Dave'),
(2, 'Thomas'),
(3, 'Paul'),
(4, 'Alex'),
(5, 'Patrick'),
(6, 'PJ')
) t
where NOT EXISTS (SELECT * FROM names);
|
|

01-27-10, 14:45
|
|
Registered User
|
|
Join Date: Jun 2009
Posts: 6
|
|
Thanks guys!
Unfortunately, it didn't!
|
|

01-27-10, 15:04
|
|
Registered User
|
|
Join Date: Feb 2008
Location: Japan
Posts: 2,193
|
|
What error message(s) did you got?
Why did you used double quotes?
Anyway, try this
Code:
INSERT INTO names(id, name)
SELECT *
FROM (VALUES
(1, 'Dave'),
(2, 'Thomas'),
(3, 'Paul'),
(4, 'Alex'),
(5, 'Patrick'),
(6, 'PJ')
) t(id, name)
WHERE (id, name) NOT IN
(SELECT id, name FROM names)
;
|
Last edited by tonkuma; 01-27-10 at 15:08.
Reason: Changed "id NOT IN ..." to "(id, name) NOT IN ..."
|

01-27-10, 15:17
|
|
Registered User
|
|
Join Date: Feb 2008
Location: Japan
Posts: 2,193
|
|
If you want to use NOT EXISTS, try this
Code:
INSERT INTO names(id, name)
SELECT *
FROM (VALUES
(1, 'Dave'),
(2, 'Thomas'),
(3, 'Paul'),
(4, 'Alex'),
(5, 'Patrick'),
(6, 'PJ')
) t(id, name)
WHERE NOT EXISTS
(SELECT *
FROM names n
WHERE n.id = t.id
AND n.name = t.name)
;
|
|

01-28-10, 08:54
|
|
Registered User
|
|
Join Date: Jun 2009
Posts: 6
|
|
Thanks!
It worked... 
|
|
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|