T-SQL extends SQL with variables, conditional logic, procedures, and server-side control flow. This hands-on tutorial connects these features to a simple product database.
Use a sample schema
Suppose dbo.Products has ProductID, ProductName, and UnitPrice. Begin with a static SELECT; it is simpler to read, tune, and secure than a dynamically assembled string.
Create a procedure
CREATE OR ALTER PROCEDURE dbo.ProductsAbovePrice
@MinPrice decimal(12,2)
AS
BEGIN
SET NOCOUNT ON;
SELECT ProductID, ProductName, UnitPrice
FROM dbo.Products
WHERE UnitPrice >= @MinPrice
ORDER BY UnitPrice DESC;
END;
GO
EXEC dbo.ProductsAbovePrice @MinPrice = 50.00;
Dynamic table choice
If a lesson requires selecting from different approved tables, look up the requested table name in a controlled allowlist and construct the SQL identifier with QUOTENAME. Pass filter values through sp_executesql parameters.
When a cursor makes sense
A cursor iterates over a result set. Its typical stages are DECLARE, OPEN, FETCH, loop, CLOSE, and DEALLOCATE. For mass updates and aggregations, a single set-based statement is usually easier and faster.
Exercises
Write a procedure with two filter parameters. Compare a cursor that processes products individually against a set-based query. Inspect estimated and actual execution plans and document the differences.
About this article: This AI-generated educational rewrite was prepared from an existing Open Education article, with new explanations and illustrative examples where helpful. Read the earlier article (post 75827). The new text may be freely copied, edited, and reused with or without attribution to this site. Third-party material, brand names, and linked resources retain their own rights. AI can make mistakes: verify syntax, version support, security practices, and outcomes against official documentation before use, especially in production.
