Results 1 to 5 of 5
  1. #1
    Join Date
    Dec 2004
    Location
    India
    Posts
    23

    Exclamation Unanswered: 'If Exists' Clause in DB2

    Hi all....
    Does DB2 UDb uses the clause 'IF EXISTS....ELSE' ????

    For eg I want to check whether a record with particular ID exists in the table.If it exists then update the remaining fields else insert a new record.
    The below query does not work:

    IF EXISTS (SELECT 'X' FROM T1 WHERE ID = 1) UPDATE T1 SET NAME = 'MMM' ELSE INSERT INTO T1 (ID,NAME) VALUES (1,'MMM')

    I tried the query UPDATE T1 SET NAME = 'MMM' WHERE EXISTS (SELECT 'X' FROM T1 WHERE ID = 1)....This query works fine but again I want the 'ELSE' part.....

    In core...How can I use the update query with conditional exists clause??????



    Thanks in advance,
    Madhuri.

  2. #2
    Join Date
    Aug 2001
    Location
    UK
    Posts
    4,650
    I think you should be able to accompolish this using a MERGE Statement, assuming you are on V8.1.2 atleast
    Visit the new-look IDUG Website , register to gain access to the excellent content.

  3. #3
    Join Date
    Jan 2005
    Location
    Rio de Janeiro - Brazil
    Posts
    28

    Just a hunch

    I don´t know where you´ll run this statement but I guess you could try to use the CASE..WHEN..THEN clause.

    CASE WHEN (<OPTION>) THEN UPDATE..
    ELSE INSERT..
    END CASE

    You can find more about this statement at the SQL Reference

  4. #4
    Join Date
    May 2010
    Posts
    21
    You might want to consider SQL/DB2 merge statement:

    DB2 Database for Linux, UNIX, and Windows

  5. #5
    Join Date
    Dec 2007
    Location
    Richmond, VA
    Posts
    1,328
    Provided Answers: 5
    you are getting a lot of "I guess" and "might" answers, because you did not tell us what the "ELSE" you want done is. If you could explain fully what you are wanting to do, you will indubitably get a more concrete answer.
    Dave Nance

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •