Stored Procedure and Function Interactive Demo

Master database operations with Fullstackgada's fun approach! ๐Ÿ—„๏ธ

๐Ÿ‘ฅ Accounts Table

Account ID Name Balance Type

๐Ÿ’ผ Employees Table

Employee ID Name Salary Performance

๐Ÿ“Š Transaction History

Transaction ID From Account To Account Amount Status Timestamp

๐Ÿ’ฐ Transfer Money

Stored Procedure: Encapsulates complex database logic for secure and efficient transactions.

๐Ÿ“ Stored Procedure Code

CREATE PROCEDURE TransferMoney( @FromAccount INT, @ToAccount INT, @Amount DECIMAL(10,2) ) AS BEGIN BEGIN TRANSACTION DECLARE @FromBalance DECIMAL(10,2) SELECT @FromBalance = Balance FROM Accounts WHERE AccountID = @FromAccount IF @FromBalance >= @Amount BEGIN UPDATE Accounts SET Balance = Balance - @Amount WHERE AccountID = @FromAccount UPDATE Accounts SET Balance = Balance + @Amount WHERE AccountID = @ToAccount INSERT INTO Transactions VALUES( @FromAccount, @ToAccount, @Amount, 'Success', GETDATE() ) COMMIT TRANSACTION RETURN 1 -- Success END ELSE BEGIN ROLLBACK TRANSACTION RETURN 0 -- Failed END END
Click Execute Transfer to run the procedure.

๐ŸŽฏ Calculate Bonus

Function: Reusable logic to compute values based on inputs, like employee bonuses.

๐Ÿ“ Function Code

CREATE FUNCTION CalculateBonus( @Salary DECIMAL(10,2), @Performance INT ) RETURNS DECIMAL(10,2) AS BEGIN DECLARE @Bonus DECIMAL(10,2) IF @Performance >= 90 SET @Bonus = @Salary * 0.20 -- 20% ELSE IF @Performance >= 80 SET @Bonus = @Salary * 0.15 -- 15% ELSE IF @Performance >= 70 SET @Bonus = @Salary * 0.10 -- 10% ELSE IF @Performance >= 60 SET @Bonus = @Salary * 0.05 -- 5% ELSE SET @Bonus = 0 -- No bonus RETURN @Bonus END -- Usage Example: SELECT Name, Salary, dbo.CalculateBonus(Salary, Performance) as Bonus FROM Employees
Click Calculate Bonus to run the function.

๐Ÿ“Š All Employees Bonus Report

๐ŸŽฏ Benefits of Stored Procedures and Functions

Aspect Regular Query Stored Procedure Function
Performance Slower due to parsing Faster (pre-compiled) Fast for reusable logic
Security Vulnerable to SQL injection Secure with parameterized inputs Secure for calculations
Reusability Repeated code Reusable across applications Reusable for computations
Maintenance Hard to update Centralized logic Centralized calculations

๐Ÿงช Performance Comparison

Regular Query

2.5s
Average Execution Time
Slow

Function

1.8s
Average Execution Time
Medium

Stored Procedure

1.2s
Average Execution Time
Fast
Click Run Performance Test to see results.

๐Ÿ’ก Pro Tips for Stored Procedures and Functions

  • ๐Ÿ”’ Use Parameters: Prevent SQL injection with parameterized queries.
  • ๐Ÿš€ Optimize Performance: Pre-compile logic with stored procedures.
  • ๐Ÿ”„ Reuse Logic: Centralize business rules in procedures and functions.
  • ๐Ÿ› ๏ธ Modularize Code: Break complex logic into smaller functions.
Pro Tip: "Make your database work smarter, not harder!" ๐Ÿ˜„