首页 > 解决方案 > 如何从 SQL 中的字符串中删除一组单词?

问题描述

我的表中有一个列,如下所示:

Column 1
-------------------------
Space Planning April 2019 
Space Décor Planning May 2020 
Hidden September 2018

如何查询以从列中删除月份和年份单词以显示类似的结果

Column 1
------------------------
Space Planning  
Space Décor Planning 
Hidden

一般来说,如何使用 SQL 从列中的字符串中动态过滤掉单词。

标签: sql-serverstring

解决方案


“一般”的方法是首先确定一些可识别的模式,该模式适用于您的特定案例中的所有数据。然后你编写利用该模式的代码。是的,我知道这听起来很奇怪。让我解释。

在您的情况下,您似乎有以下形式的模式:“某种数据”,然后是空格,然后是月份名称,然后是空格,然后是 4 位数年份。这种模式总是一致的吗?最后总是有一个4位数的年份吗?你能确定吗?如果是这样,那么您可以通过查找距值末尾超过 5 个字符的第一个空格的位置来删除月份名称和年份(这将是“数据”和“月份名称”之间的空格),然后删除它以及之后的所有内容。这是您如何做到这一点的示例。这不是唯一的方法,我试图写一个你能理解的算法。由内而外阅读!:

declare @somedata varchar(64) = 'Space Planning May 2019'

select  left
        (
            @somedata,
            len(@somedata) - 5 - charindex -- the length of the string excluding the data below
            (
                ' ', -- look for the first space character
                reverse -- reverse it
                (
                    left -- get all but the last 5 characters of the value
                    (
                        @somedata,
                        len(@somedata) - 5
                    )
                )
            )
        )

yourColumn要为我假设为名为的表中调用的整个列获取此结果YourTable,只需添加 from 子句并将变量替换为实际的列名:

select  newColumn = left
        (
            yourColumn,
            len(yourColumn) - 5 - charindex -- the length of the string excluding the data below
            (
                ' ', -- look for the first space character
                reverse -- reverse it
                (
                    left -- get all but the last 5 characters of the value
                    (
                        yourColumn,
                        len(yourColumn) - 5
                    )
                )
            )
        )
from    YourTable

推荐阅读