在SQL Server 2008中删除字符串中的所有空格的最佳方法是什么?
LTRIM(RTRIM(' a b '))将删除字符串右侧和左侧的所有空格,但我还需要删除中间的空格。
在SQL Server 2008中删除字符串中的所有空格的最佳方法是什么?
LTRIM(RTRIM(' a b '))将删除字符串右侧和左侧的所有空格,但我还需要删除中间的空格。
当前回答
简单地替换它;
SELECT REPLACE(fld_or_variable, ' ', '')
编辑: 澄清一下;它是一个全局替换,不需要trim()或担心char或varchar的多个空格:
create table #t (
c char(8),
v varchar(8))
insert #t (c, v) values
('a a' , 'a a' ),
('a a ' , 'a a ' ),
(' a a' , ' a a' ),
(' a a ', ' a a ')
select
'"' + c + '"' [IN], '"' + replace(c, ' ', '') + '"' [OUT]
from #t
union all select
'"' + v + '"', '"' + replace(v, ' ', '') + '"'
from #t
结果
IN OUT
===================
"a a " "aa"
"a a " "aa"
" a a " "aa"
" a a " "aa"
"a a" "aa"
"a a " "aa"
" a a" "aa"
" a a " "aa"
其他回答
如果你需要在所有列中修剪空格,你可以使用这个脚本来动态地做它:
--Just change table name
declare @MyTable varchar(100)
set @MyTable = 'MyTable'
--temp table to get column names and a row id
select column_name, ROW_NUMBER() OVER(ORDER BY column_name) as id into #tempcols from INFORMATION_SCHEMA.COLUMNS
WHERE DATA_TYPE IN ('varchar', 'nvarchar') and TABLE_NAME = @MyTable
declare @tri int
select @tri = count(*) from #tempcols
declare @i int
select @i = 0
declare @trimmer nvarchar(max)
declare @comma varchar(1)
set @comma = ', '
--Build Update query
select @trimmer = 'UPDATE [dbo].[' + @MyTable + '] SET '
WHILE @i <= @tri
BEGIN
IF (@i = @tri)
BEGIN
set @comma = ''
END
SELECT @trimmer = @trimmer + CHAR(10)+ '[' + COLUMN_NAME + '] = LTRIM(RTRIM([' + COLUMN_NAME + ']))'+@comma
FROM #tempcols
where id = @i
select @i = @i+1
END
--execute the entire query
EXEC sp_executesql @trimmer
drop table #tempcols
从左到右删除字符串中的空格。要消除中间空间,请使用Replace。
您可以使用RTRIM()从右边删除空格,使用LTRIM()从左边删除空格,因此左右空格被删除如下:
SELECT * FROM table WHERE LTRIM(RTRIM(username)) = LTRIM(RTRIM("Bob alias baby"))
替换特定字符的语法:
REPLACE ( string_expression , string_pattern , string_replacement )
例如,在字符串“HelloReplaceThingsGoing”中,替换词被How替换
SELECT REPLACE('HelloReplaceThingsGoing','Replace','How');
GO
为了使以上所有的答案完整,在StackOverflow上有关于如何处理所有空白字符的额外帖子(请参阅https://en.wikipedia.org/wiki/Whitespace_character获取这些字符的完整列表):
TSQL 2008使用LTrim(RTrim和仍然有空间的数据 如何从SQL server中的列中删除非间断空格? 在没有UDF和CLR的T-SQL中,从字符串中修剪所有空白字符的好方法是什么?
replace(replace(column_Name,CHAR(13),''),CHAR(10),'')