将我的表名作为 sql 查询中的参数传递
我需要查询帮助。在我的查询中,我想将表名作为参数传递。这是我的查询:
SELECT DISTINCT
CONVERT (varchar, InspectDateTime) AS 'Inspect Date Time',
CONVERT (varchar, SynDateTime) AS 'Sync Date Time',
Employee,
ROUND(OverAllPercentage, 2) AS Grade
FROM
Table_Name
WHERE
(DATEADD(dd, DATEDIFF(dd, 0, InspectDateTime), 0)
BETWEEN
DATEADD(dd, DATEDIFF(dd, 0, @From ), 0) AND
DATEADD(dd, DATEDIFF(dd, 0, @To ), 0))
ORDER BY
'Inspect Date Time'
这里我想将 Table_Name
作为参数传递。请注意,此查询已经采用两个参数作为参数,即 "@From
" 和 "@To
"
I need help with a query. In my query I want to pass my table name as parameter. This is my query:
SELECT DISTINCT
CONVERT (varchar, InspectDateTime) AS 'Inspect Date Time',
CONVERT (varchar, SynDateTime) AS 'Sync Date Time',
Employee,
ROUND(OverAllPercentage, 2) AS Grade
FROM
Table_Name
WHERE
(DATEADD(dd, DATEDIFF(dd, 0, InspectDateTime), 0)
BETWEEN
DATEADD(dd, DATEDIFF(dd, 0, @From ), 0) AND
DATEADD(dd, DATEDIFF(dd, 0, @To ), 0))
ORDER BY
'Inspect Date Time'
Here I want to pass the Table_Name
as parameter. Please note that this query is already taking two arguments as parameter, namely "@From
" and "@To
"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您正在使用 MS SQL,您可以执行以下操作:
然后调用它
If you are working with MS SQL you can do:
and then just call it
在SQL Server中,如果你想“参数化”表名,你必须使用动态SQL
如果是这样,你必须阅读 Erland的动态 SQL 的诅咒和祝福 作为介绍。
所以基本上,您需要将 SQL 语句构建为字符串,然后执行它。没有其他方法可以在 SQL Server T-SQL 语句中“参数化”表名。
In SQL Server, if you want to "parametrize" the table name, you have to use dynamic SQL
If so, you must read Erland's The Curse and Blessing of dynamic SQL as an intro.
So basically, you need to build up your SQL statement as a string, and then execute it. There is no other way to "parametrize" the table name in a SQL Server T-SQL statement.
好的,假设您使用的是 SQL Server(根据
DATEADD
和DATEDIFF
函数判断),您需要构建一个串联的 sql 命令
作为字符串(注意不要允许
SQL注入:即你应该检查
您的
table_name
变量是通过查找有效的表名
可能的名称形式
information_schema
并验证等)
使用执行动态sql
sp_executesql
:http://msdn.microsoft.com/ en-us/library/ms188001.aspxOK, assuming you're using SQL Server (judging by the
DATEADD
andDATEDIFF
functions), you'll need toconstruct a concatenated sql command
as string (taking care not to allow
SQL injection: i.e. you should check
that your
table_name
variable is avalid table name by looking up
possible names form
information_schema
and validatingetc.)
execute your dynamic sql using
sp_executesql
: http://msdn.microsoft.com/en-us/library/ms188001.aspx谢谢巴历山德。小修改后的最终查询(将@From,@To转换为varchar)是:
Thanks balexandre. The final query after minor modification(casting @From,@To into varchar) is: