Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I SELECT and then INSERT using the same data in a stored procedure?

I have a Stored Procedure that runs and needs to return data as a rowset. It also needs to use that same data to insert into another table, but I am concerned that effectively running ‘two’ concurrent SELECT statement (even within a transaction) will potentially return two different results.

How can I ensure the same data is Inserted and then output correctly?

I believe the answer lies in the OUTPUT function – I’ve tried reading documentation and examples, but it doesn’t quite seem to make sense for my scenario so wanted to check first before doing something way outside of best practice.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Example Code:

SELECT TOP 1 e.*
  FROM dbo.[example_selected_table] e

INSERT INTO dbo.[example_insert_table]
SELECT TOP 1 e.*
  FROM dbo.[example_selected_table] e

>Solution :

Use an OUTPUT clause to insert and return the inserted rows in a single-statement autocommit transaction:

INSERT INTO dbo.[example_insert_table]
OUTPUT inserted.*
SELECT TOP 1 e.*
  FROM dbo.[example_selected_table] e;

In your actual code, specify explicit column lists and an ORDER BY clause for deterministic behavior with TOP. TOP without ORDER BY may return an arbitrary row.

INSERT INTO dbo.[example_insert_table](Col1, Col2)
OUTPUT inserted.Col1, inserted.Col2
SELECT TOP 1 e.Col1, e.Col2
  FROM dbo.[example_selected_table] e
  ORDER BY e.Col1;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading