【问题标题】:Why is SQL Server 2005 Randomly Truncating Whitespace?为什么 SQL Server 2005 会随机截断空格?
【发布时间】:2009-01-05 16:14:26
【问题描述】:

以下T/SQL:-

create table #temp(foo varchar(10))

insert into #temp select ''
insert into #temp select 'abc'
insert into #temp select ' '

select len(foo) from #temp where foo = '  '

drop table #temp

返回两个 0,尽管标准意味着它不应该返回任何内容。此外,它还返回两个空白行的长度,其中一个确实长度为 0,但另一个长度为 1,都报​​告为长度 0。

有人知道这里发生了什么吗?!

更新:这似乎与 Microsoft 在 this KB article 中涵盖的 ANSI_PADDING 数据库选项有关。

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    根据文档:

    返回指定字符串表达式的字符数,不包括尾随空格。

    您应该熟悉一个名为 DataLength 的类似函数。

    create table #temp(foo varchar(10))
    
    insert into #temp select ''
    insert into #temp select 'abc'
    insert into #temp select ' '
    
    select len(foo), DataLength(foo) from #temp where foo = '  '
    
    drop table #temp
    

    出于比较目的,也删除了尾随空格。您可以通过将数据转换为 varbinary 并以这种方式进行比较来适应这一点。如果你这样做,我会保留原始比较(出于可搜索性的原因)。

    create table #temp(foo varchar(10))
    
    insert into #temp select ''
    insert into #temp select 'abc'
    insert into #temp select ' '
    
    select len(foo), DataLength(foo) 
    from    #temp 
    where   foo = ' '
            and Convert(varbinary(8), foo) = Convert(VarBinary(8), ' ')
    
    drop table #temp
    

    【讨论】:

    • 这似乎也适用于 where 子句,无论如何使 where 子句不排除尾随空格?
    • 我编辑了我的原始回复以展示一种过滤单个空间的方法。希望这会有所帮助。
    猜你喜欢
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-03
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多