简体   繁体   English

如何使用SQL Server中的预定义特殊字符修剪字符串?

[英]How to trim string using predefined special characters in SQL Server?

I want to trim SQL Server strings using some special characters such as "،,.?!؛,،,><=+ـ". 我想使用一些特殊字符修剪SQL Server字符串,例如“,,。?!; ,,,> <= +”。

The SQL server ltrim and rtrim functions only strips the space characters. SQL Server ltrim和rtrim函数仅剥离空格字符。

DECLARE @Str NVARCHAR(100) = N',,,,,!؛Computation+Time, Cost،,.?!؛,،,><=+ـ'
SELECT dbo.SpecialTrim(@Str, N'،,.?!؛,،,><=+ـ')

The result : Computation+Time, Cost

Have anyone any ideas in order to implement SpecialTrim function? 有没有人想要实现SpecialTrim功能?

The below hardcodes the pattern. 以下硬编码模式。

It looks for the first character that is not one of the characters to exclude at both ends. 它查找的第一个字符不是两端要排除的字符之一。

To make it dynamic you could build up the set of characters using string concatenation (be careful of characters containing special meaning in the pattern syntax) 要使其动态化,您可以使用字符串连接来构建字符集(注意在模式语法中包含特殊含义的字符)

WITH T(String) AS
(
SELECT 'Computation+Time, Cost،,.?!؛,،,><=+ـ' union all
SELECT ',,,,,!؛Computation+Time, Cost،,.?!؛,،,><=+ـ' union all
SELECT 'Computation+Time, Cost،,.?!؛,،,><=+ـ' union all
SELECT 'Computation+Time, Cost' union all
SELECT ''
)
SELECT SUBSTRING(String,Start,len(String) + 2 - Start - Finish)
FROM T
CROSS APPLY
(
SELECT  PATINDEX('%[^،,.?!؛,،,><=+ـ]%' COLLATE Latin1_General_Bin,String),
        PATINDEX('%[^،,.?!؛,،,><=+ـ]%' COLLATE Latin1_General_Bin,REVERSE(String))
)ca(Start, Finish)

From SQL Server vNext and on you could use built-in TRIM function: SQL Server vNext开始 ,您可以使用内置的TRIM功能:

TRIM 修剪

Removes white spaces or specified characters from a string. 从字符串中删除空格或指定字符。

 TRIM ( [ characters FROM ] string ) 

Returns a character expression with a type of string argument where white spaces or specified characters are removed from both sides. 返回字符串参数类型的字符表达式,其中从两侧删除空格或指定字符。 Returns NULL if input string is NULL. 如果输入字符串为NULL,则返回NULL。

In your case: 在你的情况下:

DECLARE @Str NVARCHAR(100) = N',,,,,!؛Computation+Time, Cost،,.?!؛,،,><=+ـ';
SELECT TRIM(N'،,.?!؛,،,><=+ـ' FROM @Str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM