SQL Server从字符串中删除尾随空格
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL Server从字符串中删除尾随空格相关的知识,希望对你有一定的参考价值。
我有一个包含字符串数据类型的列。我不明白为什么删除空格后字符的数量仍然是10或者是否有我错过的东西?
select top(5)
[SECOND OCCURANCE] as [Date 2],
len([SECOND OCCURANCE]) as [CharDate2],
len(REPLACE([SECOND OCCURANCE], ' ', '')) as [NewCharDate2],
[Second Occurance] = case when len([SECOND OCCURANCE]) = 10
then(right(CONCAT('0', [SECOND OCCURANCE]), 11))
else [SECOND OCCURANCE]
end
from
UFO_MERGED
输出:
Date 2 CharDate2 NewCharDate2 Second Occurance
--------------------------------------------------------
06/12/2008 10 10 006/12/2008
11/28/2007 11 11 11/28/2007
12/16/2005 11 11 12/16/2005
04/09/2004 11 11 04/09/2004
5/15/2006 10 10 05/15/2006
答案
在SQL Server中,CHAR的数据类型保存字符数,无论它们是否已填充。因此,如果单词小于11,则CHAR(11)
将填充空格。如果列为VARCHAR(11),则如果字符串的长度短于列的大小,则将自动修剪空格。
考虑到空间仍然显示在计数中,可能需要以二进制检查值。
试试看没有十六进制编辑器的二进制值:
SELECT
CONVERT(varbinary(11), [SECOND OCCURANCE]) AS DateInBinary
FROM UFO_MERGED
根据您的编码,您可能会得到像这样的结果0x352f31352f32303036
您可以查找值以查看您正在拉动的角色。我匹配此页面https://ascii.cl/htmlcodes.htm所以'5'= 35和'/'= 2f等。
一旦找到二进制值,就可以像REPLACE([SECOND OCCURANCE],CHAR(<binary value>),'')
之前那样使用替换然后尝试捕获坏数据混入记录的位置。
另一答案
您可以尝试使用LTRIM
+ RTRIM
。
TRIM
函数在SQL Server 2017上可用:
select top(5)
[SECOND OCCURANCE] as [Date 2]
,len([SECOND OCCURANCE]) as [CharDate2]
,len([LTRIM(RTRIM(SECOND OCCURANCE]))) as [NewCharDate2]
,[Second Occurance] = case when len([SECOND OCCURANCE]) = 10
then(right(CONCAT('0',[SECOND OCCURANCE]),11))
else [SECOND OCCURANCE] end
from UFO_MERGED
另一答案
请运行这个:
select top(5)
'"' + [SECOND OCCURANCE] + '"' as [raw]
,len([SECOND OCCURANCE]) as [rawLen]
,'"' + ltrim(rtrim([SECOND OCCURANCE])) + '"' as [rawTrim]
,len(ltrim(rtrim([SECOND OCCURANCE])) as [rawTrimLen]
from UFO_MERGED
这将为您提供有关您的数据的信息。你可能有一些控制角色。
使用这样的东西来找到控制字符并用''
(空字符串)替换它们:
declare @s varchar(10) = 'Hogan ' + char(9) + ' ';
select '"' + @s + '"' as raw
, convert(varbinary, @s) as rawHex
, '"' + ltrim(rtrim(@s)) + '"' as trim
, convert(varbinary, ltrim(rtrim(@s))) as trimHex
以上是关于SQL Server从字符串中删除尾随空格的主要内容,如果未能解决你的问题,请参考以下文章