Is this incorrect, can't we pass the table name to a select query dynamically?
This is giving me a error 'Must declare the table variable @TblName'
DECLARE @TblName VARCHAR(30)
SET @TblName = 'User'
SELECT *
FROM @TblName
Is this incorrect, can't we pass the table name to a select query dynamically?
This is giving me a error 'Must declare the table variable @TblName'
DECLARE @TblName VARCHAR(30)
SET @TblName = 'User'
SELECT *
FROM @TblName
You need to create a dynamic SQL query, preferably using the QUOTENAME function. You can avoid any issues from malicious input by using QUOTENAME function.
Here is a sample script that illustrates how to query a table by creating a dynamic SQL query by passing in a table name. You can change the table name by value to the variable @tablename
.
CREATE TABLE sample
(
id INT NOT NULL
);
INSERT INTO sample (id) VALUES
(1),
(2),
(3),
(4),
(5),
(6);
DECLARE @execquery AS NVARCHAR(MAX)
DECLARE @tablename AS NVARCHAR(128)
SET @tablename = 'sample'
SET @execquery = N'SELECT * FROM ' + QUOTENAME(@tablename)
EXECUTE sp_executesql @execquery
Click here to view the demo in SQL Fiddle.
you have to use dynamic
sql execution
wrap your statement in @selectstr
use exec sp_executesql @selectstr
You can do this thing by using dynamic query, Check below
DECLARE @TblName VARCHAR(30)
DECLARE @vQuery NVARCHAR(100)
SET @TblName = 'User'
SET @vQuery = 'SELECT * FROM ' + @TblName
EXECUTE sp_executesql @vQuery