top of page

SQL- Stored procedure: Skip first two INSERT statements

I encounter an interesting question as follows:

You have a stored procedure that needs to run three INSERT statements, the first two of which should all complete or all not complete. The third INSERT should run no matter what, succeeding/failing independently. How do you code this?

 

Say you have the following simple table:

CREATE TABLE Examples.ThreeInsert ( ThreeInsertID int CONSTRAINT PKThreeInsert PRIMARY KEY)

You can code something like the following.

In code destined for production work, you likely want to code nested TRY...CATCH blocks, and save the error messages from the first two INSERT statements in variables to throw at the end.

CREATE PROCEDURE Examples.ThreeInsert_Create @SecondValue int = 2 -- Define a parameter as int to pass values, int ranges -2,147,483,648 to +2,147,483,648 AS Set NOCOUNT ON BEGIN TRY BEGIN TRANSACTION; INSERT INTO Examples.ThreeInsert(ThreeInsertID) VALUES(1) INSERT INTO Examples.ThreeInsert(ThreeInsertID) VALUES(@SecondValue) COMMIT TRANSACTION; END TRY BEGEIN CATCH IF XACT_STATE() <> 0 -- if XACT_STATE() = 0, then it means that there is no active user transaction for the current result. ROLLBACK TRANSACTION; --Here no throw, it will mean no reporting of message END CATCH; INSERT INTO Examples.ThreeInsert(ThreeInsertID) VALUES(3);


aboutME

I am John Fan Zhang, a data analyst and finance researcher. I hold a PhD in finance, CFA charter and full membership of CFA New Zealand Society. I have fifteen-year experience in corporate investment and eight-year experience in advanced data analysis. My research focuses on the effect of social psychology (culture) on financial decisions. Finance research involves heaps of data analyses that lead me to the data field. I am a Microsoft Certified Solutions Expert (MCSE): Data Management and Analytics (Excel, Power BI, and SQL). Aside from Excel, Power BI and SQL, I am also familiar with econometric tools such as Stata, Eviews, and MATLAB. I use OX and Python for programming. I am an active data community event participant, volunteer, speaker, moderator, program reviewer, including PASS Marathon 2020, Global AI BootCamp Auckland 2019, SQL Saturday Auckland (2017, 2018, 2019), and Definity Conference (2018, 2019, 2020, Auckland, New Zealand).

Auckland, New Zealand

  • Google Site
  • Twitter
  • LinkedIn

©2016 BY JOHN'S DATA STORY

bottom of page