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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 and insert script for sample:
Dynamic SQL script:
Demo:
Click here to view the demo in SQL Fiddle.
Suggested read:
The Curse and Blessings of Dynamic SQL