为查询字符串声明变量
我想知道在 MS SQL Server 2005 中是否有办法做到这一点:
DECLARE @theDate varchar(60)
SET @theDate = '''2010-01-01'' AND ''2010-08-31 23:59:59'''
SELECT AdministratorCode,
SUM(Total) as theTotal,
SUM(WOD.Quantity) as theQty,
AVG(Total) as avgTotal,
(SELECT SUM(tblWOD.Amount)
FROM tblWOD
JOIN tblWO on tblWOD.OrderID = tblWO.ID
WHERE tblWO.Approved = '1'
AND tblWO.AdministratorCode = tblWO.AdministratorCode
AND tblWO.OrderDate BETWEEN @theDate
)
... etc
这可能吗?
I was wondering if there was a way to do this in MS SQL Server 2005:
DECLARE @theDate varchar(60)
SET @theDate = '''2010-01-01'' AND ''2010-08-31 23:59:59'''
SELECT AdministratorCode,
SUM(Total) as theTotal,
SUM(WOD.Quantity) as theQty,
AVG(Total) as avgTotal,
(SELECT SUM(tblWOD.Amount)
FROM tblWOD
JOIN tblWO on tblWOD.OrderID = tblWO.ID
WHERE tblWO.Approved = '1'
AND tblWO.AdministratorCode = tblWO.AdministratorCode
AND tblWO.OrderDate BETWEEN @theDate
)
... etc
Is this possible to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是可能的,但它需要使用动态 SQL。
我建议在继续之前阅读动态 SQL 的诅咒和祝福...
动态 SQL 只是一种 SQL语句,在执行之前组成一个字符串。因此发生了通常的字符串连接。每当您想要使用 SQL 语法执行不允许的操作时,就需要动态 SQL,例如:
EXEC sp_executesql
允许您使用bind/preparedstatement参数,因此您不必担心转义单引号/等以进行SQL注入攻击。It's possible, but it requires using dynamic SQL.
I recommend reading The curse and blessings of dynamic SQL before continuing...
Dynamic SQL is just a SQL statement, composed as a string before being executed. So the usual string concatenation occurs. Dynamic SQL is required whenever you want to do something in SQL syntax that isn't allowed, like:
EXEC sp_executesql
allows you to use bind/preparedstatement parameters so you don't have to concern yourself with escaping single quotes/etc for SQL injection attacks.然后更改您的查询以使用以下逻辑:
Then change your query to use this logic:
使用 EXEC
您可以使用以下示例来构建 SQL 语句。
使用 sp_executesql
通过使用此方法,您可以确保传递到查询中的数据值是正确的数据类型,并避免使用更多引号。
参考
Using EXEC
You can use following example for building SQL statement.
Using sp_executesql
With using this approach you can ensure that the data values being passed into the query are the correct datatypes and avoind use of more quotes.
Reference
我将指出,在评分最高的答案中链接的文章动态 SQL 的诅咒和祝福 作者指出,答案是不使用动态SQL。几乎滚动到最后可以看到这一点。
来自文章:“正确的方法是将列表解压到带有用户定义函数或存储过程的表中。”
当然,一旦列表位于表中,您就可以使用联接。我无法直接对评分最高的答案发表评论,所以我只是添加了此评论。
I will point out that in the article linked in the top rated answer The Curse and Blessings of Dynamic SQL the author states that the answer is not to use dynamic SQL. Scroll almost to the end to see this.
From the article: "The correct method is to unpack the list into a table with a user-defined function or a stored procedure."
Of course, once the list is in a table you can use a join. I could not comment directly on the top rated answer, so I just added this comment.