Testing spaces in SQL Server

I have several empty values โ€‹โ€‹in my table, and I cannot catch them in the IF statement.

I tried

IF @value = '' and if @value = NULL , and none of them catch empty values. Is there any way to check if varchar is completely space?

Aha! Turns out I tested the error. Thank you

+6
sql sql-server whitespace
source share
8 answers

To compare with NULL, use the IS NULL keyword.

 --Generic example: SELECT * FROM MY_TABLE WHERE SOME_FIELD IS NULL; --Instead of SELECT * FROM MY_TABLE WHERE SOME_FIELD = NULL; 
+8
source share
 ltrim(rtrim(isNull(@value,''))) = '' 
+10
source share

if length (@value) = 0 or @value is null

+3
source share

(LTRIM (RTRIM (@Value)) = '' should do the trick.

+3
source share

where length (rtrim (ltrim (yourcolumnname))) = 0 OR column_name is null

+2
source share

Instead of doing over-string manipulation with LTRIM AND RTRIM , just search for the expression for the first "non-space".

 SELECT * FROM [Table] WHERE COALESCE(PATINDEX('%[^ ]%', [Value]), 0) > 0 
+2
source share

I just did some testing and found out something interesting. I wrote my queries like this:

 SELECT * FROM TableA WHERE Val IS NOT NULL AND LEN(RTRIM(LTRIM(Val))) > 0 

But you really don't need to check for null, all you have to do is check the length after trimming the value.

 SELECT * FROM TableA WHERE LEN(RTRIM(LTRIM(Val))) > 0 

This option preempts zeros, as well as any columns with a space.

As it turns out, you don't need to trim the value because SQL Server ignores trailing spaces, so all you really need is: SELECT * FROM TableA WHERE LEN (Val)> 0

+1
source share

You may have fields with multiple spaces (''), so you will get better results if you trim this:

 where ltrim(yourcolumnname) = '' 
0
source share

All Articles