0

I need to write a query in Oracle, but I'm more familiar with SQL Server.

In SQL Server, the query would look as follows: (simplified)

if exists (
    select * from table where a=1
)
begin
    update table set b=1 where a=1 
end else 
begin 
    insert table (a,b) values(1,1) 
end

Thanks for any help :)

===============================================================================

This is the Merge option, (I think):

MERGE INTO table T
USING (
    SELECT a,b
    FROM table
) Q
ON T.a = Q.a
WHEN MATCHED THEN
    UPDATE SET T.a = 1
WHEN NOT MATCHED THEN
    INSERT table (a,b) VALUES (1,1);

Is this correct?

4
  • Use the merge statement. Commented Mar 7, 2013 at 10:58
  • What does that mean? Can you give an example relating to the above SQL? Thanks Commented Mar 7, 2013 at 11:01
  • Stackoverflow can give plenty of them to you. ;) stackoverflow.com/search?q=oracle+merge Commented Mar 7, 2013 at 11:02
  • I added what I think is the right usage of MERGE - does this look right? Thanks Commented Mar 7, 2013 at 11:14

1 Answer 1

2

This should be the correct syntax for Oracle 11g. I'm not an expert on Oracle so maybe someone else could explain it better, but I believe the dual table is used when inserting new values instead or trying too merge is from another table.

MERGE INTO table1 T
USING (
    SELECT 1 a, 1 b FROM dual
) Q
ON (T.a = Q.a)
WHEN MATCHED THEN
    UPDATE SET b = 1
WHEN NOT MATCHED THEN 
    INSERT (a,b) VALUES (Q.a,Q.b);

Working example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.