Dynamic SQL query: set table name
In dynamic SQL queries, you can use certain methods to dynamically provide parameters and set the table name. Although you have successfully set a parameter, you now need guidance on how to set the table name dynamically.
Dynamicly set table name
To prevent SQL injection vulnerabilities, it is recommended to use functions whenever possible. In this case, you can combine several techniques to set the table name dynamically:
<code class="language-sql">SET @TableName = '<[db].><[schema].>tblEmployees' SET @TableID = OBJECT_ID(@TableName) --如果格式错误/注入,则无法解析。 SET @SQLQuery = 'SELECT * FROM ' + QUOTENAME(OBJECT_NAME(@TableID)) + ' WHERE EmployeeID = @EmpID'</code>
This script initializes the table name as a parameter and then retrieves the underlying object ID to ensure the provided name is valid. If the provided table name is malformed or has been injected as a SQL vulnerability, the object ID will not resolve.
Finally, make a reference to the table name to avoid potential SQL injection attacks and complete the dynamic SQL query by adding the provided employee ID parameter.
The above is the detailed content of How Can I Dynamically Set Table Names in Dynamic SQL Queries to Prevent SQL Injection?. For more information, please follow other related articles on the PHP Chinese website!