'SQL Select table name

A database had has 4 tables that has the same columns EG. SalesJAn, SalesFeb, SalesMarch, SalesApril.

I want to run a query in SQL server or in report builder Where i can change the table name based on a selection which one of 4 tables will be queried . Eg Filter in report builder

Like this

declare @tablename varchar(50) set @tablename = 'test' select * from @tablename



Solution 1:[1]

You can create a procedure which will do a select for a given table name. This procedure could look like this:

CREATE PROCEDURE EXECUTE_SELECT
@tbl sysname
AS
BEGIN
 SET NOCOUNT ON;
 DECLARE @SQL NVARCHAR(MAX);
 SET @SQL =  N' SELECT * FROM ' + QUOTENAME(@tbl)
 EXECUTE sp_executesql @SQL 
END 

Then you can execute this procedure for every table name you want. Please see here an example according to your description: db<>fiddle

If this doesn't help you, please point out which exactly you still need to know. Thank you.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonas Metzler