SQL Server修剪字符串

时间:2018-09-19 07:25:01

标签: sql sql-server trim

我有一个查询,我想修剪一列并获取唯一的右侧值:

enter image description here

在图片中,结果类似于SubAccountCodeSubaccountName,但是用户在SubaccountName中输入了代码和名称。我想修剪Subaccountname中的代码并更新表格。 T

下面提到了我尝试过的查询,但是我认为它不是那么有效:

 Select Substring(Subaccountname,8,20)as Name from #temp

2 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。 查看示例数据时,最简单的方法是在更新语句中使用replace()

语法: REPLACE ( string_expression , string_pattern , string_replacement )

示例:

UPDATE table_name
SET column2 = replace([column2], [column1], '')

这是怎么做的,用column2中的值更新column2,其中column1中的值替换为” none”。在您的示例中,这确实使您在前面留有多余的空间。您可以修剪它或尝试如下操作:

UPDATE Test
SET [SubAccountName] = replace([SubAccountName], [SubAccountCode] + ' ', '')

如果SubAccountCodeSubAccountName中的代码不同,并且您只想删除前8个字符(如果您确定始终是前8个字符),则可以使用:< / p>

UPDATE YourTable SET SubAccountName = RIGHT(SubAccountName, LEN(SubAccountName) - 7)

示例脚本:

create table test (
    SubAccountName varchar(100),
    SubAccountCode varchar(100)
    )

insert into test (SubAccountCode, SubAccountName) VALUES
(1234567, '1234567 AUBC' ),
(1234467, '1234467 AUBC' ),
(1235567, '1235567 AUBC' )

select * from test -- Check that the data is like your example.

UPDATE Test SET SubAccountName = RIGHT(SubAccountName, LEN(SubAccountName) - 8)

select * from test -- Check that the result is like your wanted result.

drop table test -- Cleanup the test table.

答案 1 :(得分:1)

此代码将为您服务。

UPDATE TableName SET SubaccountName = REPLACE(LTRIM(RTRIM(SubaccountName)),LTRIM(RTRIM(SubAccountCode)),'')