The safest way to do this is through presentation.
Create a view that combines all the tables that you might want to access (and which should have the same column structure), and the row prefix with the table name.
CREATE VIEW MultiTable
AS
SELECT 'table1' AS TableName, * FROM table1
UNION ALL
SELECT 'table2' AS TableName, * FROM table2
UNION ALL
SELECT 'table3' AS TableName, * FROM table3
Your stored procedure can now filter the table name:
CREATE PROCEDURE test
@TableName varchar(100)
AS
SELECT * FROM MultiTable WHERE TableName = @TableName
This is safer than using and creating dynamic SQL.
source
share