问题
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