How do I check if a Sql server string is null or e

2020-01-25 12:35发布

I want to check for data but ignore it if it's null or empty. Currently the query is as follows...

Select              
Coalesce(listing.OfferText, company.OfferText, '') As Offer_Text,         
from tbl_directorylisting listing  
 Inner Join tbl_companymaster company            
  On listing.company_id= company.company_id      

But I want to get company.OfferText if listing.Offertext is an empty string, as well as if it's null.

What's the best performing solution?

17条回答
The star\"
2楼-- · 2020-01-25 13:03

In SQL Server 2012 you have IIF, e.g you can use it like

SELECT IIF(field IS NULL, 1, 0) AS IsNull

The same way you can check if field is empty.

查看更多
一夜七次
3楼-- · 2020-01-25 13:04

I know this is an old thread but I just saw one of the earlier posts above and it is not correct.

If you are using LEN(...) to determine whether the field is NULL or EMPTY then you need to use it as follows:

...WHEN LEN(ISNULL(MyField, '')) < 1 THEN NewValue...
查看更多
手持菜刀,她持情操
4楼-- · 2020-01-25 13:05

[Column_name] > ' ' excludes Nulls and empty strings. There is a space between the single quotes.

查看更多
等我变得足够好
5楼-- · 2020-01-25 13:09

I think this:

SELECT 
  ISNULL(NULLIF(listing.Offer_Text, ''), company.Offer_Text) AS Offer_Text
FROM ...

is the most elegant solution.

And to break it down a bit in pseudo code:

// a) NULLIF:
if (listing.Offer_Text == '')
  temp := null;
else
  temp := listing.Offer_Text; // may now be null or non-null, but not ''
// b) ISNULL:
if (temp is null)
  result := true;
else
  result := false;
查看更多
家丑人穷心不美
6楼-- · 2020-01-25 13:09

To prevent the records with Empty or Null value in SQL result

we can simply add ..... WHERE Column_name != '' or 'null'

查看更多
登录 后发表回答