使用局部变量作为“IN” SQL Server 的标准条件
可能的重复:
SQL:storedprocedure 中的 in 子句:如何传递值 < /p>
I我正在使用 MS SQL Server 2005,并尝试基本上编写一个两步过程的脚本:
- 在表中查询匹配特定条件的 ID 列表
- 更新该表中的字段,其中 ID 位于以下列表中:第一个返回的 ID
问题是步骤 1 和 2 可能会被相当长的时间延迟分开并在不同的会话中执行。 #2 中使用的 ID 列表本质上是历史数据:#1 在过去的时间点返回的值。
我尝试做的是以“##、##、##、##”格式将 #1 中的所有 ID 写入 varchar(8000)(这部分效果很好),然后使用该字符串就像:
UPDATE table SET field=newValue WHERE (id IN (@varcharOfCommaSeparatedIDs))
但这给了我一个语法错误,指出它无法将该 varchar 值转换为所需的任何内容(错误消息被截断)
有没有办法做到这一点,而无需将整个 SQL 命令放入字符串中并执行该命令(使用 EXEC 或sp_executesql)?经过多年避免注入攻击后,我对“动态 SQL”有一种本能的(也许是非理性的)厌恶
Possible Duplicate:
SQL : in clause in storedprocedure:how to pass values
I'm using MS SQL Server 2005, and trying to basically script a 2-step process:
- Query a table for a list of IDs matching certain criteria
- Update a field in that table, where the ID is in the list of IDs returned by the first
With the catch being that steps 1 and 2 might be separated by a considerable time delay and executed in different sessions. Essential the list of IDs used in #2 is historical data: the values which #1 returned at a past point in time.
What I've attempted to do is write all of IDs from #1 into a varchar(8000) in "##, ##, ##, ##," format (this part is working great), and then use that string like:
UPDATE table SET field=newValue WHERE (id IN (@varcharOfCommaSeparatedIDs))
But this is giving me a syntax error, stating that it cannot convert that varchar value into whatever is needed (the error message is being truncated)
Is there a way to do this without putting the entire SQL command into a string and executing that (using EXEC or sp_executesql)? After years of avoiding injection attacks I have a somewhat instinctive (and perhaps irrational) aversion to "dynamic SQL"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您要在 SQL Server 上的 SP 之间传递值,我强烈建议将这些值存储在表中...
- 临时表 (#mytable)
- 表变量(@table)
- 真实表
在 SQL Server 2008 及以后的版本中,您可以使用表值输入参数...
如果您从应用程序中传递值,则可怕的逗号分隔字符串确实很有用。 SO 上有很多答案,它们提供了表值函数,用于将字符串转换为 id 表,读取后进行连接。
If you're passing the values around between SP's on the SQL Server, I highly recommend storing the values in tables...
- Temp Tables (#mytable)
- Table Variables (@table)
- Real Tables
In SQL Server 2008 onwards you can have table valued input parameters...
If you're passing the values in from an app, the dread comma-separated-string is indeed useful. There are many answers on SO that give Table Valued Functions for turning a string into a table of ids, read to be joined on.
只需将其写到表中即可。
然后,稍后:
另请注意,如果您愿意,还可以在表上使用
INNER JOIN
而不是IN
子句。Just write it out to a table.
Then, later:
Also note you could also use an
INNER JOIN
on your table instead of aIN
clause if you prefer.