在两个已知字符串之间选择一个字符串的 SQL 查询 [英] A SQL Query to select a string between two known strings

查看:29
本文介绍了在两个已知字符串之间选择一个字符串的 SQL 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 SQL 查询来获取两个已知字符串之间的值(返回的值应该以这两个字符串开头和结尾).

I need a SQL query to get the value between two known strings (the returned value should start and end with these two strings).

一个例子.

我只知道这只狗很坏,不管其他人怎么想,都要立即受到严厉的惩罚."

"All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought."

在这种情况下,已知字符串是狗"和立即".所以我的查询应该返回这只狗很坏,需要立即严厉惩罚"

In this case the known strings are "the dog" and "immediately". So my query should return "the dog had been very bad and required harsh punishment immediately"

到目前为止我已经想出了这个但无济于事:

I've come up with this so far but to no avail:

SELECT SUBSTRING(@Text, CHARINDEX('the dog', @Text), CHARINDEX('immediately', @Text))

@Text 是包含主字符串的变量.

@Text being the variable containing the main string.

有人可以帮我解决哪里出错了吗?

Can someone please help me with where I'm going wrong?

推荐答案

问题是子字符串参数的第二部分包含第一个索引.您需要从第二个索引中减去第一个索引才能完成这项工作.

The problem is that the second part of your substring argument is including the first index. You need to subtract the first index from your second index to make this work.

SELECT SUBSTRING(@Text, CHARINDEX('the dog', @Text)
, CHARINDEX('immediately',@text) - CHARINDEX('the dog', @Text) + Len('immediately'))

这篇关于在两个已知字符串之间选择一个字符串的 SQL 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆