sql - 如何检索关键字前后的一定数量的字符?

标签 sql sql-server t-sql sql-server-2012

我正在使用 SQL Server 2012 来查询数据。

其中一列是自由格式文本框,我需要该列中的数据,但我不希望返回整个段落。我想查找像“obsolete”这样的关键字,并检索它前面的 20 个字符和后面的 20 个字符。

如果我将解决方案应用于以下段落,其中我正在查找单词 obsolete 及其前后的 20 个字符:

In 1992, Tim Berners-Lee circulated a document titled “HTML Tags,” which outlined just 20 tags, many of which are now obsolete or have taken other forms. The first surviving tag to be defined in the document, after the crucial anchor tag, is the paragraph tag. It wasn’t until 1993 that a discussion emerged on the proposed image tag.

它将返回:“其中任何一个现已过时或已采用其他”

注意:我是最终用户,而不是管理员,因此请不要建议我,如果这是一个问题,我们不应该允许自由格式的文本框。

最佳答案

您可以使用此查询获得结果:

DECLARE @Paragraph nvarchar(max) = 'In 1992, Tim Berners-Lee circulated a document titled “HTML Tags,” which outlined just 20 tags, many of which are now obsolete or have taken other forms. The first surviving tag to be defined in the document, after the crucial anchor tag, is the paragraph tag. It wasn’t until 1993 that a discussion emerged on the proposed image tag.'
DECLARE @Keyword nvarchar(50) = 'obsolete'

SELECT SUBSTRING(@Paragraph, CHARINDEX(@Keyword, @Paragraph) - 20, LEN(@Keyword) + 40)

关于sql - 如何检索关键字前后的一定数量的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46918700/

相关文章:

SQL Server 2008 字段函数 - 根据其他两个字段之间的关系返回 'ok' 或 'no'

sql - 为什么这会加速我的 SQL 查询?

sql - 从连接查询中选择最新数据的前 1 个

sql - Postgres SQL 状态 : 54000 when copying data to table

c# - SQL 查询不起作用

SQL 查询以选择特定的列值并连接它们

sql-server - 将多个子表关联到一个父表

sql-server - 服务器对象在 SQL Server Management Studio 中不可用

sql - 在记录水平上标记差异

SQL Server : use function to calculate a new column