What is Dynamic SQL?
Building SQL queries as text strings, then executing them.
Simple analogy: Like writing a sentence, then reading it out loud.
Basic Example
-- Build query as string
SET @table_name = 'students';
SET @sql_query = 'SELECT * FROM ' || @table_name;
-- Execute it
EXECUTE @sql_query;When to Use
Use when:
- Table name varies
- Column names change
- Conditions are dynamic
Example: Search different tables based on user choice
SET @search_table = 'products'; -- Could be 'orders', 'customers', etc.
SET @query = 'SELECT * FROM ' || @search_table || ' LIMIT 10';
EXECUTE @query;Warning
Be careful with user input! Can be risky (SQL injection).
Never do this:
SET @query = 'SELECT * FROM users WHERE name = ' || user_input;
-- DANGEROUS if user_input is malicious!Summary
Dynamic SQL = Build queries as strings Powerful but use carefully Validate all inputs