| 
View
 

Lecture - Getting Started with Transactions in T-SQL

Page history last edited by Dr. Ron Eaglin 11 years, 10 months ago

Getting Started with Transactions in T-SQL

 

 

Summary of Video

 

Covers the ACID test and how to perform transactions using stored procedures with T-SQL

 

Prerequisites

 

Lecture - Getting Started with Stored Procedures in SQL Server

 

Video Link

 

http://online1.daytonastate.edu/player2.php?id=75b9b6dc7fe44437c6e0a69fd863dbab 

 

 

Support Materials

 

 

 

CREATE PROCEDURE [dbo].[performTransaction]
(
  @FromAccountID INT,
  @ToAccountID INT, 
  @Amount FLOAT
)
AS
BEGIN
-- Check to see if accounts exist
DECLARE @FromAccountTest INT
SELECT @FromAccountTest = (SELECT Count(*) 
  FROM Accounts
  WHERE AccountID = @FromAccountID)
IF @FromAccountTest <> 1 
BEGIN
 RAISERROR('From Account Does Not Exist', 10, 1)
END
DECLARE @ToAccountTest INT
SELECT @ToAccountTest = (SELECT Count(*) 
  FROM Accounts
  WHERE AccountID = @ToAccountID)
IF @FromAccountTest <> 1 
BEGIN
 RAISERROR('To Account Does Not Exist', 10, 2)
END
-- At this point we can log the transaction
DECLARE @TransactionID INT 
EXEC @TransactionID = LogTransactionAttempt @FromAccountID, @ToAccountID, @Amount 
-- Check to see if sufficient balance
DECLARE @FromAccountBalance  FLOAT
SELECT @FromAccountBalance = (SELECT Balance
    FROM Accounts 
    WHERE AccountID = @FromAccountID)
    
IF (@FromAccountBalance < @Amount)     
BEGIN
  RAISERROR('Insufficient Balance', 10, 3)
END
-- Now we can start the transaction
BEGIN TRANSACTION 
UPDATE Accounts
 SET Balance = Balance - @Amount
 WHERE AccountID = @FromAccountID
IF (@@ERROR <> 0)
   BEGIN
    ROLLBACK TRANSACTION   /* if errors - rollback transaction */
    RETURN 
   END
 
UPDATE Accounts
 SET Balance = Balance + @Amount
 WHERE AccountID = @ToAccountID
 
IF (@@ERROR <> 0)
   BEGIN
    ROLLBACK TRANSACTION   /* if errors - rollback transaction */
    RETURN 
   END
UPDATE TransactionLog
  SET Successful = 1
  WHERE TransactionID = @TransactionID
 
IF (@@ERROR <> 0)
   BEGIN
    ROLLBACK TRANSACTION   /* if errors - rollback transaction */
    RETURN 
   END
-- Transaction
COMMIT TRANSACTION
END -- Procedure 

 

CREATE PROCEDURE [dbo].[LogTransactionAttempt]
(
  @FromAccountID INT,
  @ToAccountID INT, 
  @Amount FLOAT
)
 AS
 BEGIN
  INSERT INTO TransactionLog
  (
    FromAccountID,
    ToAccountID,
    Amount, 
    TransactionDate
  )
  VALUES 
  (
    @FromAccountID,
    @ToAccountID,
    @Amount,
    GETDATE()
  )
 
  RETURN @@IDENTITY
 
  END 

 

 

 

 

 

All Materials Copyright 2012 Dr. Ron Eaglin

Comments (0)

You don't have permission to comment on this page.