2009-01-05 54 views
1

下面的T/SQL: -SQL Server 2005爲什麼隨機截斷空白?

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.

是否有人知道這裏發生了什麼?

更新:看起來這與微軟在this KB article中涵蓋的ANSI_PADDING數據庫選項有關。

回答

5

根據文檔:

返回指定字符串表達式的字符數,不包括尾隨空白。

有一個名爲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 
+0

這似乎也適用於where子句,無論如何使where子句不排除尾隨空白? – ljs 2009-01-05 16:27:23