sql-stored-procedure-001
Dynamic View for All E_ Tables in SQL Server
Problem
You want a SQL Server view that combines all tables whose names start with the prefix E_, even though those tables are being created and deleted over time.
Limitation
In SQL Server:
- A view cannot be truly dynamic.
- A view must be compiled against specific objects and columns.
- If tables are added or removed, the view will not automatically update.
So the correct approach is to dynamically rebuild the view definition whenever the table list changes.
Recommended Solution (Option A)
Stored Procedure that Rebuilds the View
Concept:
- Query system tables to find all
E_%tables. - Build a
UNION ALLquery across them. - Recreate the view using dynamic SQL.
- Run the procedure on a schedule or after table changes.
Requirements
You must choose a column strategy:
Option 1 – All E_ tables have identical schema
- Easiest scenario.
Option 2 – Use a template table
- A table (for example
dbo.E_Template) defines the canonical column list. - Only tables matching those columns are included.
Option 3 – Use only shared columns
- More complex.
- Only columns common across all tables are included.
The script below uses Option 2 (Template Table).
Stored Procedure: Rebuild the View
1 | CREATE OR ALTER PROCEDURE dbo.Rebuild_v_E_All |