在SQL Server表的字段末尾删除一些字符串

时间:2019-04-05 19:03:02

标签: sql sql-server

我的SQL Server表中有一列名为brn_description,其中包含以下数据:

Minneapolis c0 02/14/18
Sacramento c0 02/14/18
Vancouver c0 02/14/18

我要删除所有这些“ c0 02/14/18”。大约是11个字符。

我该如何删除这些,然后返回

Minneapolis 
Sacramento 
Vancouver 

6 个答案:

答案 0 :(得分:1)

尝试以下代码: 将@str替换为您的列名

Declare @str Nvarchar(MAX) ='Minneapolis c0 02/14/18' SELECT left(@str,len(@str)-11)

答案 1 :(得分:1)

如果您的字符串固定,则可以使用REPLACE

Declare @str Nvarchar(MAX) ='Minneapolis c0 02/14/18'
SELECT REPLACE(@str, 'c0 02/14/18', '');

demo

答案 2 :(得分:0)

您可能想要:

update t
    set brn_description = left(brn_description, len(brn_description) - 11)
    where col like '% c0 [0-9][0-9]/[0-9][0-9]/[0-9][0-9]';

这实际上更改了显示此模式的列的值。

答案 3 :(得分:0)

只要有尾随空格或CRLF等,我会选择查找 c0 而不是修剪最后11个字符

Declare @S varchar(max) = 'Minneapolis c0 02/14/18'

Select left(@S,charindex(' c0 ',@S+' c0 ')-1)

答案 4 :(得分:0)

UPDATE brn_description SET column = LEFT(column, LEN(column) - 12)

在这种情况下,或者,您可以使用CHARINDEX,因为空格非常明显

UPDATE brn_description SET column = LEFT(column, CHARINDEX(' ', column) - 1)

答案 5 :(得分:0)

您可能要删除右边第二个空格之后的所有内容(如果有“ Los Angeles”,则不能使用左边的第一个空格)。在字符串charindex()上用reverse()找到该空间的索引。一旦获得它,就可以从用len()得到的字符串的长度中减去它,并用left()从左边取那么多的字符(长度是相同的,无论是否颠倒,这就是为什么会这样)。

SELECT left(brn_description, len(brn_description) - charindex(' ', reverse(brn_description), charindex(' ', reverse(brn_description)) + 1))
       FROM (SELECT 'Minneapolis c0 02/14/18' brn_description
             UNION ALL
             SELECT 'Sacramento c0 02/14/18' brn_description
             UNION ALL
             SELECT 'Vancouver c0 02/14/18' brn_description
             UNION ALL
             SELECT 'Los Angeles c0 02/14/18' brn_description) x;