SQL Server: T-SQL Features: Concept
Module: Database-Specific Features
T-SQL (Transact-SQL) is Microsoft's procedural extension to standard SQL. While standard SQL is declarative (you say what you want), T-SQL adds procedural capabilities (you can control how to get it). Think of standard SQL as ordering food at a restaurant - you specify what you want. T-SQL is like having a kitchen where you can control the cooking process step-by-step. This matters because complex business logic often requires conditional logic, loops, and error handling that standard SQL cannot provide.
**1. Variables and Data Types**
Variables store intermediate results and parameters. Declared with DECLARE, assigned with SET or SELECT.
```sql
-- Declare variables
DECLARE @OrderCount INT;
DECLARE @TotalRevenue DECIMAL(10,2);
DECLARE @CustomerName NVARCHAR(100);
-- Assign with SET (single value)
SET @OrderCount = (SELECT COUNT(*) FROM orders WHERE status = 'completed');
-- Assign with SELECT (can set multiple variables)
SELECT @TotalRevenue = SUM(total_amount),
@OrderCount = COUNT(*)
FROM orders
WHERE order_date >= '2024-01-01';
-- Use in queries
SELECT * FROM orders WHERE total_amount > @TotalRevenue / @OrderCount;
```
**Why this matters**: Stripe uses variables to store payment thresholds and fraud detection scores during transaction processing. Variables reduce query complexity and make logic reusable.
**2. Control Flow Statements**
IF/ELSE for conditional logic, WHILE for loops, CASE for inline conditions.
```sql
-- IF/ELSE example
DECLARE @OrderCount INT = (SELECT COUNT(*) FROM orders);
IF @OrderCount > 1000
BEGIN
PRINT 'High volume - enable batch processing';
UPDATE settings SET batch_mode = 1;
END
ELSE IF @OrderCount > 100
BEGIN
PRINT 'Medium volume - standard processing';
UPDATE settings SET batch_mode = 0;
END
ELSE
BEGIN
PRINT 'Low volume - real-time processing';
UPDATE settings SET batch_mode = 0, realtime = 1;
END;
-- WHILE loop example (use sparingly)