将字符串传递到 SQL WHERE IN
我正在开发一个查询页面,用户在其中选择代表不同类型的值,每个类型都由 ID 标识。 问题是使用 WHERE IN 方法从数据库中选择这些 ID。
这是我的 SQL 语句,
SELECT M.REG_NO, T.TYPE_ID
FROM MAIN AS M
INNER JOIN CLASSIFICATION AS C
ON M.REG_NO = C.REG_NO
INNER JOIN TYPE AS T
ON T.TYPE_ID = C.TYPE_ID
WHERE T.TYPE_ID IN (@Types)
它将适用于一个值,例如。 46,但如果该值位于括号中则不是,例如。 (46) 或 ('46'),IN 应该如此。
我正在使用 Visual Studio,它会自动生成访问表适配器以获取值的方法,因此我认为我必须通过 SQL 来执行此操作。
我正在传递一个字符串,例如。 Types = "46,267,2010" ,进入适配器方法,该方法将字符串传递到 SQL 语句中的 @Types 中。
任何帮助都会很棒。谢谢!
I am working on a query page where a user selects a value which represents different types, each identified by an ID.
The problem is selecting these IDs from the data base using the WHERE IN method.
This is my SQL statement
SELECT M.REG_NO, T.TYPE_ID
FROM MAIN AS M
INNER JOIN CLASSIFICATION AS C
ON M.REG_NO = C.REG_NO
INNER JOIN TYPE AS T
ON T.TYPE_ID = C.TYPE_ID
WHERE T.TYPE_ID IN (@Types)
it will work for one single value, eg. 46, but NOT if the value is in brackets, eg. (46) or ('46'), the way it should be for the IN.
I am using visual studio which is auto generating the method to access the table adapter to get the values so I think I HAVE to do this through SQL.
I am passing a string, eg. Types = "46,267,2010" , into the adapter method which passes the string into the @Types in the SQL statement.
Any help would be great. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个非常常见的问题——不知道为什么 TSQL 还没有处理它。无论如何,我发现最适合我的解决方案是将变量转换为表,然后您可以对其使用 IN() 就可以了。
从函数开始:
然后使用函数...
This is a pretty common problem -- not sure why TSQL hasn't dealt with it yet. Anyway, the solution I've found works best for me is to convert the variable to a table, and then you can use IN() on it just fine.
Starting with the function:
And then to use the function...
这是因为您需要一组用逗号分隔的值。比如
你使用的是SQL Server还是Oracle、MySQL?
如果您有一个由多个值组成的字符串,例如
您可能需要一个函数来使用分隔符分解您的字符串(拆分或任何调用,具体取决于您的 DBMS)
It's because you need to have a set of values separated by commas. Like
Are you usign SQL Server or Oracle, MySQL?
If you have a string composed of your multiple values such as
You might need a function that will explode your string usign a delimiter (split or whatever it is called depending on you DBMS)
以下
Select
对我来说工作正常:The following
Select
working fine for me: