问题
I want to set table name in a dynamic SQL query. I tried successfully for parameter as following:
/* Using sp_executesql */
/* Build and Execute a Transact-SQL String with a single parameter
value Using sp_executesql Command */
/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = \'SELECT * FROM tblEmployees WHERE EmployeeID = @EmpID\'
/* Specify Parameter Format */
SET @ParameterDefinition = \'@EmpID SMALLINT\'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID
Now I want to take TABLE NAME
dynamically using a parameter but I\'ve failed to do that. Please guide me.
回答1:
Table names cannot be supplied as parameters, so you'll have to construct the SQL string manually like this:
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID'
However, make sure that your application does not allow a user to directly enter the value of @TableName
, as this would make your query susceptible to SQL injection. For one possible solution to this, see this answer.
回答2:
To help guard against SQL injection, I normally try to use functions wherever possible. In this case, you could do:
...
SET @TableName = '<[db].><[schema].>tblEmployees'
SET @TableID = OBJECT_ID(TableName) --won't resolve if malformed/injected.
...
SET @SQLQuery = 'SELECT * FROM ' + OBJECT_NAME(@TableID) + ' WHERE EmployeeID = @EmpID'
回答3:
Try this:
/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @TableName AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
SET @TableName = 'tblEmployees'
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID'
/* Specify Parameter Format */
SET @ParameterDefinition = '@EmpID SMALLINT'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID
回答4:
This is the best way to get a schema dynamically and add it to the different tables within a database in order to get other information dynamically
select @sql = 'insert #tables SELECT ''[''+SCHEMA_NAME(schema_id)+''.''+name+'']'' AS SchemaTable FROM sys.tables'
exec (@sql)
of course #tables is a dynamic table in the stored procedure
来源:https://stackoverflow.com/questions/20678725/how-to-set-table-name-in-dynamic-sql-query