SQL Isnull is not working and returns a value even if it is a space

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-14 03:29:09

问题


I am using SQL Server 2016 and came across an issue with the isnull function. The value in that field is a space but keeps getting selected, below is my code:

SELECT * FROM table
WHERE  isnull (field1,'')<>''
       AND field1<>' '

If I copy and paste from field1, it is one space ' '.

Thanks


回答1:


Your space is not normal space (hex 0x20, decimal 32)

select ASCII(LEFT(field1, 1), * From table
where  isnull (field1,'')<>''

Most likely it is one of

  • Linefeed decimal 10
  • Carriage return decimal 13
  • Null decimal 0
  • hard space decimal 160
  • tab decimal 9 (as per comments on question from @SeanLange)



回答2:


I have tried to put every possible combination in insert.. try this

Create table #t(Field1 varchar(100))
Insert into #t values 
(NULL), (' '), ('  '), ('a'),('')


select  field1 From #t
where LTRIM(RTRIM(field1)) <> ''

output :

field1
---------
a



回答3:


As we found out through comments and other answers (gbn's especially) there could be other invisible characters except space.

But that doesn't give you a solution how to write your query which could be something like:

where field1 NOT IN (CHAR(0), CHAR(9), CHAR(10), CHAR(11), CHAR(12), CHAR(13), CHAR(14), CHAR(32), CHAR(160))



回答4:


I found the solution for this issue as:

SELECT ISNULL(NULLIF(field1,''), field2)


来源:https://stackoverflow.com/questions/45461543/sql-isnull-is-not-working-and-returns-a-value-even-if-it-is-a-space

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!