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 );
LVL 34
Mike EghtebasDatabase and Application DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Koen Van WielinkBusiness Intelligence SpecialistCommented:
No, the book is correct. What they mean I'd that you can't use the variable directly in a query.
This for example will throw an error:

DECLARE @tablename AS NVARCHAR(261) = N'[Production].[Products]';
SELECT COUNT(*) FROM @tablename; 

Open in new window

When you use dynamic SQL, you create a string value where you insert the parameters into the string. When this string is formed, the parameter names are replaced with their values, leaving you with a well-formed query string. This is then executed used the Exec() function. The trick is to put the parameters outside of string quotes when creating the string value. If you would include the parameter in quotes as well it's that's as a string and you get the same error as when not using dynamic sql.
Good practice is to print your dynamic sql string so you can see the difference. Try replacing

Open in new window

print @sqlstring 

Open in new window

to see what actually happens when the query executes.
DECLARE @SQLString AS NVARCHAR(4000) = ' ...................... '  + @tablename

that line 2 of your code is NOT a FROM CLAUSE, it is the declaration of a variable

                    although it does contain A STRING of sql that will become a from clause

but it does not become a from clause until that string is executed (in line 3)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
HuaMin ChenProblem resolverCommented:
Try to follow the syntax below
CREATE PROCEDURE InsertSales @PrmOrderID INT, @PrmCustomerID INT,
                 @PrmOrderDate DATETIME, @PrmDeliveryDate DATETIME
DECLARE @InsertString NVARCHAR(500)

-- Build the INSERT statement.
SET @InsertString = 'INSERT INTO ' +
       /* Build the name of the table. */
       SUBSTRING( DATENAME(mm, @PrmOrderDate), 1, 3) +
       CAST(DATEPART(yy, @PrmOrderDate) AS CHAR(4) ) +
       'Sales' +
       /* Build a VALUES clause. */
       ' VALUES (@InsOrderID, @InsCustID, @InsOrdDate,' +
       ' @InsOrdMonth, @InsDelDate)'

/* Set the value to use for the order month because
   functions are not allowed in the sp_executesql parameter
   list. */
SET @OrderMonth = DATEPART(mm, @PrmOrderDate)

EXEC sp_executesql @InsertString,
     N'@InsOrderID INT, @InsCustID INT, @InsOrdDate DATETIME,
       @InsOrdMonth INT, @InsDelDate DATETIME',
     @PrmOrderID, @PrmCustomerID, @PrmOrderDate,
     @OrderMonth, @PrmDeliveryDate


Open in new window

Vitor MontalvãoMSSQL Senior EngineerCommented:
eghtebas, I think the answers from Koen and Paul are very clear but do you need some more clarification?
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.