SQL Server从字符串中删除尾随空格

时间:2018-03-02 15:11:46

标签: sql sql-server sql-server-2008

我有一个包含字符串数据类型的列。我不明白为什么删除空格后字符的数量仍然是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

3 个答案:

答案 0 :(得分:0)

在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>),'')之前那样使用替换,然后尝试捕获错误数据混入记录的位置。

答案 1 :(得分:0)

您可以尝试使用LTRIM + RTRIM

SQL Server 2017上提供了

TRIM功能:

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

答案 2 :(得分:0)

请运行:

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