Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server - how do i find rows with whitespace in a column

I want to do something like

select * from X where string.IsNullOrWhiteSpace(a)

Column a is NOT NULL

So what would be the equivalent of C# string.IsNullOrWhiteSpace in T-SQL to get all rows where column a has only whitespace (combination of multiple spaces or tabs)?

Also, I would rather avoid using clr functions.

like image 598
MoXplod Avatar asked Jun 10 '14 16:06

MoXplod


People also ask

How do I select a column that contains spaces in SQL?

To select a column name with spaces, use the back tick symbol with column name. The symbol is ( ` `). Back tick is displayed in the keyboard below the tilde operator ( ~).

How do you find if a string contains a space in SQL?

SELECT * FROM MYTABLE WHERE INSTR(ColumnName,' ') > 0; Essentially in this query it finds the character position containing first space from the column values and when it finds the first space in it the index value should be greater than 1 and it should display all the records based on that.

How do you handle column names with spaces in SQL?

DML SQL query with space in a column name When we run INSERT, UPDATE, and DELETE statements, we must use a square bracket or double quotes to handle the column name with space.


2 Answers

You could try this:

select * 
from yourtable
where ltrim(rtrim(yourcolumn)) = ''

The idea is that if trimming the value leaves you with an empty string, then all you had in the first place was whitespace.

You could also just do this:

select *
from yourtable
where yourcolumn like ' '

Note that I have tested the second query on SQL Server 2008 R2, and it doesn't work on 2014 as stated in the comments by @gunr2171

Finally, if you have tab, carriage return or line feed, the above will not work. What you can do is to first replace these values with a blank string, and then use the first query like so:

select * 
from yourtable
where ltrim(rtrim(replace(replace(replace(yourcolumn,char(9),''),char(10),''),char(13),''))) = ''

char(9),char(10) and char(13) are used for tab, line feed and carriage return respectively.

like image 175
shree.pat18 Avatar answered Oct 18 '22 14:10

shree.pat18


I just had a problem with this particular situation, i needed to find and clean every field with white spaces, but i found 4 types of possibles white space in my database fields (Reference to ASCII code table):

  • Horizontal Tab(char(9))
  • New Line(char(10))
  • Vertical Tab(char(9))
  • Space(char(32))

Maybe this query can help you.

SELECT @COLUMN
FROM @TABLE
WHERE @COLUMN like '%'+CHAR(9)+'%' or @COLUMN like '%'+CHAR(10)+'%'
or @COLUMN like '%'+CHAR(11)+'%' or @COLUMN like '%'+CHAR(32)+'%'
like image 41
sami.almasagedi Avatar answered Oct 18 '22 12:10

sami.almasagedi