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.
7条答案
按热度按时间6jygbczu1#
You could try this:
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:
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:
char(9)
,char(10)
andchar(13)
are used for tab, line feed and carriage return respectively.bz4sfanl2#
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 ):
Maybe this query can help you.
7y4bm7vi3#
Based on shree.pat18's comment, here's a possible answer...
I think that should do the trick
jhdbpxl94#
I would try something like this
After examining my query it would appear redundant to use ltrim AND rtrim, just use one or the other.
the following will suffice
kcrjzv8t5#
For full ASCII whitespace (tabs, line feeds, spaces, etc) and the flexibility to add other characters as needed, i.e CHAR(0):
qgzx9mmu6#
Method
string.IsNullOrWhiteSpace
checks for 25 different unicode whitespace characters. For an equivalent check in SQL Server 2017+ we can use the TRIM function:Since in this question
a
is not null, that part can be left out from theWHERE
clause.In lower versions of SQL Server, trimming specific characters requires a bit more effort, so in most cases, a regular LTRIM should be enough. But if you do need the exact C# equivalent, you can see how to trim specific characters here:
ni65a41a7#
Here is an example of an If statement that checks if a variable is null or whitespace (c# equivalent of
IsNullOrWhitespace
).You can make this inline by including the logic in a where clause.