4

I want to insert values based on below code to a temporary table in postgresql

declare @output table (AuditScratchID bigint, AuditID bigint);

merge table atb
 using (select 
            s.ID
            ....
            ....
            ....
        from @temporaryTableVariable s
            inner join ....
...............
..............

        ) as s
 on 1 = 2 -- Impossible Condition so they never match
 when not matched then
    insert (.....)
    values (.....)
    output s.ID, inserted.ID
    into @output;

Just to mention, how can I correlate values into temporary table

6
  • I don't understand what that MERGE is supposed to do if you force it to never match? Isn't that a simple insert into ... select from temp_table in the end? Commented Apr 14, 2020 at 8:14
  • It is, the op has even stated that with the comment on 1 = 2 -- Impossible Condition so they never match Commented Apr 14, 2020 at 8:21
  • @Andronicus: the question is: why? Why is this necessary in SQL Server instead of a simply insert into .. select from ...? Commented Apr 14, 2020 at 8:26
  • I am doing a migration from SQL Server to PostgreSQL. Client has such code written, hence i wanted to know how can i handle output clause and insert record in PostgreSQL Commented Apr 14, 2020 at 8:34
  • 1
    the reason you want to force an insert on a merge statement in MSSQL is because the OUTPUT clause of a merge statement in MSSQL has access to columns that do not exist in the target table. Commented May 27, 2024 at 21:26

1 Answer 1

4

I don't understand the use of MERGE to begin with.

This seems like a straightforward insert ... select. To see the inserted rows, use the returning clause

insert into atb (...)
select ... columns ...
from some_table
  join other_table on ...
returning *
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.