SQL Transactions – Example

So, as I wrote yesterday, I needed to create a Transaction for my SQL database.  If you’ll remember, my database was a hypothetical library in Africa.  A new book needs cataloged, and since the book table is interlinked with several other tables, you don’t want one of the inserts to succeed and another to fail, because then your tables won’t match, and that’s all bad.  So you group all the inserts into one batch called a transaction and thus ensure data integrity.  So here we insert a book into the book table, an author into the author table, and a category into the category table all at once.  Creative Commons license blah blah blah.

DECLARE @BookID int

DECLARE @AuthorID int

DECLARE @Category_ID int

BEGIN TRY

BEGIN TRAN;

INSERT Authors VALUES (‘Coppen’, ‘Ben’);

SET @AuthorID = @@IDENTITY;

INSERT Categories VALUES (‘Computers’);

SET @Category_ID = 3;

INSERT Books

Values(0763732303, ‘Artificial Intelligence Illuminated’, @AuthorID, 2004, 1,@Category_ID, NULL);

COMMIT TRAN;

END TRY

BEGIN CATCH

ROLLBACK TRAN;

END CATCH;

Advertisements

One thought on “SQL Transactions – Example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s