SQL:使用 IN 子句将字符串转换为 IDS
DECLARE @STR_IDS VARCHAR(15)
SET @STR_IDS='7,15,18'
UPDATE TBL_USERS WHERE ID IN @STR_IDS
我知道更新语句不起作用,因为 ID 是 INT 类型,并且我正在替换那里的 varachar 值。我如何更改查询,以便它实际上像这样执行?
UPDATE TBL_USERS WHERE ID IN (7,15,18)
提前致谢
DECLARE @STR_IDS VARCHAR(15)
SET @STR_IDS='7,15,18'
UPDATE TBL_USERS WHERE ID IN @STR_IDS
I know the update statement would not work as the ID is of type INT and i am replacing a varachar value there .How can i change the query so that it will be executed like this in effect ?
UPDATE TBL_USERS WHERE ID IN (7,15,18)
Thanks in advace
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Op 没有提到数据库,所以我只使用 SQL Server,因为问题中的示例 SQL 看起来像 TSQL。 SQL Server 中有多种分割字符串的方法。本文涵盖了几乎每种方法的优点和缺点:
"数组和列表SQL Server 2005 及更高版本,当表值参数无法分割时”作者:Erland Sommarskog
您需要创建一个拆分函数。这是分割函数的使用方式:
我更喜欢数字表方法在 TSQL 中分割字符串,但在 SQL Server 中分割字符串的方法有很多种,请参阅前面的链接,其中解释了每种方法的优点和缺点。
要使 Numbers Table 方法发挥作用,您需要执行此一次时间表设置,这将创建一个包含 1 到 10,000 行的
Numbers
表:设置 Numbers 表后,创建此拆分函数:
您现在可以轻松地将 CSV 字符串拆分为表并连接它或根据需要使用它,甚至可以在动态 sql 中。以下是如何根据您的问题使用它:
Op doesn't mention database, so I'll just use SQL Server, because the example SQL in the question looks like TSQL. There are many ways to split string in SQL Server. This article covers the PROs and CONs of just about every method:
"Arrays and Lists in SQL Server 2005 and Beyond, When Table Value Parameters Do Not Cut it" by Erland Sommarskog
You need to create a split function. This is how a split function can be used:
I prefer the number table approach to split a string in TSQL but there are numerous ways to split strings in SQL Server, see the previous link, which explains the PROs and CONs of each.
For the Numbers Table method to work, you need to do this one time table setup, which will create a table
Numbers
that contains rows from 1 to 10,000:Once the Numbers table is set up, create this split function:
You can now easily split a CSV string into a table and join on it or use it however you need, even from within dynamic sql. Here is how to use it from your question:
最近我更喜欢使用用户定义的表类型来传递参数列表,但我曾经使用这个实用函数:
你可以像这样使用它:
Lately I prefer to use User-Defined Table Types to pass lists of parameters, but I used to use this utility function:
You'd use it like this:
盗自此处:
正确做法:
Stolen from here:
The just do:
对于 mysql 来说真的很简单
只需使用FIND_IN_SET函数
for mysql its really easy
just use FIND_IN_SET function