0
merge into Mytable WITH (HOLDLOCK) as dst
                    using (select @mId as MId,  
                        @up as UP, 
                        @termsAccepted as TermsAccepted, 
                        @AnalyticsAccepted as AnalyticsAccepted, 
                        @EssentialCookiesPolicyWasAccepted as EssentialAccepted,

                    ) as src on dst.MId = src.MId and dst.UP = src.UP
                when matched then 
                    update set dst.TermsAccepted = src.TermsAccepted,
                        dst.AnalyticsAccepted = src.AnalyticsAccepted,
                        dst.EssentialAccepted = src.EssentialAccepted,

                when not matched then
                    insert(MId, UP ) 
                    values(src.MId, src.UP)

Trying to convert this into postgres but cant seem to find a reason syntax replacement for merge?

tried a recursive query but slightly lost on how deep to go?

WITH f AS (
select mId as MId,  
up as UP, 
) as src on dst.MId = src.MId and dst.UP = src.UP
)
INSERT INTO myTable (MId, UP) 
SELECT src.MId, src.UP
FROM src
WHERE NOT EXISTS (
insert(MId, UP ) 
values(src.MId, src.UP)
                           
4
  • 1
    Good answer here on how Postgres 9.5+ "INSERT ON CONFLICT (key) DO UPDATE...` Insert syntax that should work as a replacement to MERGE in sql server. Commented Jun 23, 2021 at 14:48
  • thanks, I have used insert into but I cannot seem to understand the recursion part of it. still working o nit Commented Jun 23, 2021 at 15:14
  • I don't think there is any need for recursion here. You are upserting/merging from one table/result-set into another table based on a key. Whether thats UPSERT, MERGE, INSERT INTO ... ON DUPLICATE KEY... INSERT INTO ... ON CONFLICT... it's more or less a sql syntax question. Commented Jun 23, 2021 at 15:50
  • im not too sure what you mean, could you provide an example? Commented Jun 23, 2021 at 16:01

2 Answers 2

1

Not sure what the Microsoft SQL server statement does exactly, but you can try something like:

INSERT INTO mytable (mid, up) VALUES ($1, $2)
ON CONFLICT (mid, up)
DO UPDATE SET mid = EXCLUDED.mid, up = EXCLUDED.up;

This requires a unique constraint on (mid, up).

The columns in the UPDATE branch in your question have different names, but that doesn't make any sense to me. Replace details as necessary!

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

2 Comments

apologies, bit of incorrect copy and past there. fixed with correct columbs added
Ok, makes sense now. Just use the actual column names instead of the ones in my answer then.
1

The MERGE command is available as of Postgres 15.

MERGE documentation

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.