在 SQL Server 2000 中将字符串拆分为多个值
我是代表我客户的某个人问我这个问题的。我其实对mySQL比SQL Server更熟悉,但不幸的是,SQL Server是客户端使用多年的。
问题基本上是这样的:SQL Server 中是否有一种方法可以将字符串拆分为可在 WHERE 语句中使用的多个值(例如数组?)。
这是我正在讨论的 PHP 示例。
<?php
$string = "10,11,12,13";
$explode = explode(",", $string);
?>
$explode 将等于 array(10,11,12,13)。我需要做的是这样的:
SELECT {long field list] FROM {tables} WHERE hour IN SPLIT(",", "10,11,12,13")
SPLIT 是执行分割的伪代码函数
我不在 PHP 中执行此操作的原因是因为查询是由报告软件构建,在将其发送到数据库之前我们无法执行逻辑(例如我的 PHP 代码),并且软件将多个值作为由管道 (|) 分隔的单个字符串返回。
不幸的是,我无法访问报告软件(我认为他说它被称为 Logi 或 LogiReports 或其他东西)或我的同事正在起草的查询,但对于这个问题来说,真正重要的是 WHERE 子句。
有什么想法吗?
I'm asking the question on behalf of someone that works for my client that asked me this. I'm actually more familiar with mySQL than SQL Server, but unfortunately, SQL Server is what the client has used for years.
The question basically this: Is there a way in SQL Server to split a string into multiple values (e.g. array?) that can be used in a WHERE statement.
Here's a PHP example of what I'm talking about.
<?php
$string = "10,11,12,13";
$explode = explode(",", $string);
?>
$explode would be equal to array(10,11,12,13). What I need to do is something like this:
SELECT {long field list] FROM {tables} WHERE hour IN SPLIT(",", "10,11,12,13")
With SPLIT being my pseudo-code function that performs the splitting
The reason why I'm not doing this in, let's say, PHP, is because the query is being constructed by reporting software where we can't perform logic (such as my PHP code) before sending it to the database, and the multiple values are being returned by the software as a single string separated by pipes (|).
Unfortunately I do not have access to the reporting software (I think he said it was called Logi or LogiReports or something) or the query my associate was drafting up, but all that is really important for this question is the WHERE clause.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可以使用动态SQL:
Dynamic SQL can be used:
这里有几种方法: SQL Server 中的数组和列表
对于短字符串,我更喜欢 数字表
我可以从这里复制/粘贴,但它真的值得一读
Several methods here: Arrays and list in SQL Server
For short strings, I prefer a numbers table
I could copy/paste from here but it really is worth reading
您可以使用一个函数,该函数接收包含由管道分隔的“id”的字符串,并将其作为表返回,您可以在子查询中查询和使用它,如下所示:
You could use a Function which receives a string containing the "id's" separated by pipes, and return it as a table, which you can query and use in a subquery maybe, like this:
您可以使用此存储过程。
我希望这对你有用。
you can use this stored procedure.
I hope that be useful for you.