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;