Sql-server – How to use same stored procedure for different tables and avoid using dynamic sql

dynamic-sqlsql serverstored-procedures

I have quite a few tables which contain some common columns (same name and datatype). On these columns I need to perform the same operations and I would like to do that via a stored procedure. However the only way I can make it work at the moment is using dynamic sql, which I'd rather avoid.

Is there any way to use a stored procedure for different tables (where the table name is handed over as parameter) without using dynamic sql?

Best Answer

The other thing you could do is create a view that unions the like tables together, and include a defined column with the table name, then just do a select against that view with the tablename in the where clause.

CREATE VIEW tablesviews AS
SELECT columns, 'TABLE1' as tablename
FROM Table1
UNION ALL
SELECT columns, 'TABLE2' as tablename
FROM Table2
...


SELECT {some columns}
FROM  tableviews
WHERE Tablename=@table and [other where clauses]