在SQL Server 2008中删除字符串中的所有空格的最佳方法是什么?
LTRIM(RTRIM(' a b '))将删除字符串右侧和左侧的所有空格,但我还需要删除中间的空格。
在SQL Server 2008中删除字符串中的所有空格的最佳方法是什么?
LTRIM(RTRIM(' a b '))将删除字符串右侧和左侧的所有空格,但我还需要删除中间的空格。
当前回答
如果字符串中有多个空格,则replace可能无法正常工作。为此,应该使用下面的函数。
CREATE FUNCTION RemoveAllSpaces
(
@InputStr varchar(8000)
)
RETURNS varchar(8000)
AS
BEGIN
declare @ResultStr varchar(8000)
set @ResultStr = @InputStr
while charindex(' ', @ResultStr) > 0
set @ResultStr = replace(@InputStr, ' ', '')
return @ResultStr
END
例子:
select dbo.RemoveAllSpaces('aa aaa aa aa a')
输出:
aaaaaaaaaa
其他回答
我分享一个解决方案,在我看来,它非常快,但安装起来有点繁琐。它在Microsoft SQL Server 2008 R2 (SP3)上工作得很好:
在数据库所在的服务器上安装Sql Regex程序集。安装步骤如下: https://github.com/DevNambi/sql-server-regex#installation 在数据库中创建函数dbo。TRIM,它基于RegexReplace()标量函数(https://github.com/DevNambi/sql-server-regex#replace):
CREATE FUNCTION [dbo].[TRIM](@text NVARCHAR(MAX))
RETURNS NVARCHAR(MAX) --WITH SCHEMABINDING
BEGIN
-- This function removes:
-- 1. invisible characters,
-- 2. repeated blank spaces and
-- 3. the spaces at the beginning and at the end of the text.
RETURN (CASE
WHEN @text is NULL
THEN NULL
ELSE
dbo.RegexReplace((dbo.RegexReplace(dbo.RegexReplace(@text, N'['+Nchar(0)+N'-'+Nchar(32)+Nchar(8192)+N'-'+Nchar(8202)+Nchar(160)+Nchar(5760)+Nchar(6158)+Nchar(8232)+Nchar(8233)+Nchar(8239)+Nchar(8287)+Nchar(65440)+Nchar(12288) +N']+', N'[}'), N'[\[\}]+', ' ')), N'^\s+|\s+$','')
END);
END
GO
....................
使用方法:
declare @txt NVARCHAR(MAX) = N' Hello,'+Nchar(12288)+N' my '+NCHAR(160)+N'name'+Nchar(0)+N' is John'+NCHAR(11)+N' Doe';
select dbo.TRIM(@txt) as Result -- Result: "Hello, my name is John Doe"
....................
更新:
要完全删除所有空格,您可以创建以下函数:
CREATE FUNCTION [dbo].[TRIM_SPACES](@text NVARCHAR(MAX))
RETURNS NVARCHAR(MAX) --WITH SCHEMABINDING
BEGIN
RETURN (CASE WHEN @text is NULL THEN NULL ELSE
dbo.RegexReplace(@text, N'['+Nchar(0)+N'-'+Nchar(32)+Nchar(8192)+N'-'+Nchar(8202)+Nchar(160)+Nchar(5760)+Nchar(6158)+Nchar(8232)+Nchar(8233)+Nchar(8239)+Nchar(8287)+Nchar(65440)+Nchar(12288) +N']+', N'')
END)
END
GO
....................
使用方法:
declare @txt NVARCHAR(MAX) = N' Hello,'+Nchar(12288)+N' my '+NCHAR(160)+N'name'+Nchar(0)+N' is John'+NCHAR(11)+N' Doe';
select dbo.TRIM_SPACES(@txt) as Result -- Result: "Hello,mynameisJohnDoe"
取代()函数:
REPLACE(field, ' ', '')
如果是对表的更新,则必须多次运行此更新,直到影响到0行为止。
update tableName
set colName = REPLACE(LTRIM(RTRIM(colName)), ' ', ' ')
where colName like '% %'
如果你想从字符串中删除空格,-和另一个文本,那么使用以下命令:
假设您的表格中有一个手机号码,如“718-378-4957”或 ' 7183784957',你想要替换并获得手机号码,然后使用下面的文本。
select replace(replace(replace(replace(MobileNo,'-',''),'(',''),')',''),' ','') from EmployeeContactNumber
结果:——7183784957
如果正规空格没有被LTRM或RTRM删除,请尝试这样使用
LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(Column_data, CHAR(9), ''), CHAR(10), ''), CHAR(13), '')))