Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello i want to use a variable after '.' operator like this:
SQL
SELECT * FROM DestinationDatabase.dbo.@TableName

Yet i get syntax error. Any idea on how to circumvent this?
Appreciating the help.
Posted
Updated 8-Sep-14 3:49am
v2

You need to use Dynamic SQL

There is an SQL command called sp_ExecuteSQL

This will allow you build a string such as this and execute it:

SQL
DECLARE @MySQL VARCHAR(MAX)
SET @MySQL = 'SELECT * FROM DestinationDatabase.dbo.' + @TableName
EXEC sp_ExecuteSQL @MySQL


WARNING!!! WARNING!!! WARNING!!!

Make sure you understand the security implications of using dynamic SQL. Most website hacks are done by injecting addition SQL into dynamic SQL executions.

This is the MSDN article for sp_ExecuteSQL

http://msdn.microsoft.com/en-gb/library/ms188001.aspx[^]

This is a article with covers the security risks.

The Curse and Blessings of Dynamic SQL[^]
 
Share this answer
 
Comments
Mehdi Gholam 8-Sep-14 10:05am    
5'ed
You can't use variables (starting with @) for table names in SQL, if you need to be dynamic either :

1) create your queries on the client in string format and execute on your server.
2) create a sql string variable of your query and EXEC() it (be aware that SQL permissions of the user executing will apply).
 
Share this answer
 
Comments
YourAverageCoder 8-Sep-14 9:59am    
For your second point i tried sp_executesql. Here's how i did it:
SET @dynamicSQLCommand = 'SELECT * FROM DestinationDatabase.dbo.@TableName'
EXEC sp_executesql @dynamicSQLCommand, N'@TableName nvarchar(500)', @TableName = @copiedTableName
Yet i still got the syntax error in first row of the code.
Mehdi Gholam 8-Sep-14 10:06am    
See the solution 2 for this.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900