Link to home
Start Free TrialLog in
Avatar of Mike Eghtebas
Mike EghtebasFlag for United States of America

asked on

Dynamic SQL

Reading a book with a Q/A:

Q: What are some objects that cannot be referenced in T-SQL by using variables?
A: 1- database name in a USE statement,
   2- table name in a FROM clause,
   3- column names in the SELECT and WHERE clauses,
   4- lists of literal values in the IN() and PIVOT() functions.

My Question: With focus on item 2 above, the following code runs fine with table name stored in variable. Is the answer in the book wrong on item 2 or I am misinterpreting something?

DECLARE @tablename AS NVARCHAR(261) = N'[Production].[Products]';
DECLARE @SQLString AS NVARCHAR(4000) = 'use TSQL2012; ' + 'SELECT COUNT(*) FROM ' + @tablename
exec ( @SQLString );
SOLUTION
Avatar of Koen Van Wielink
Koen Van Wielink
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
eghtebas, I think the answers from Koen and Paul are very clear but do you need some more clarification?