declare @var nvarchar(500)='Software Development'
select @var as NotTrim
select LTRIM(RTRIM(@var)) as Trim
期望输出是“软件开发”(单词介于两个单词之间)
答案 0 :(得分:3)
尝试以下
SELECT
s,
LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(s,' ',' ^'),'^ ',''),'^','')))
FROM (SELECT ' Q W E ' s) q
^
- 您可以使用字符串中未包含的任何符号。
我在论坛sql.ru
上找到了这种方法。
此方法将任何空格数替换为一个空格。我多次使用这种方法,我认为它运作良好。
你的例子
declare @var nvarchar(500)='Software Development'
select @var as NotTrim
select LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(@var,' ',' ^'),'^ ',''),'^',''))) as Trim
您可以逐步了解它的工作原理
SELECT
s,
-- step 1 - add special char before to each spaces
REPLACE(s,' ',' ^'),
-- step 2 - delete special char and space after this special char
REPLACE(REPLACE(s,' ',' ^'),'^ ',''),
-- step 3 - delete special chars
REPLACE(REPLACE(REPLACE(s,' ',' ^'),'^ ',''),'^',''),
-- step 4 - delete start and end spaces if you need it
LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(s,' ',' ^'),'^ ',''),'^','')))
FROM (SELECT ' Q W E ' s) q
答案 1 :(得分:2)
试试这个,
DECLARE @var NVARCHAR(500)='Software Development'
SELECT @var AS NotTrim
SELECT Trimmed = REPLACE(REPLACE(REPLACE(@var,' ','<>'),'><',''),'<>',' ')
希望这有帮助。