我想检查数据,但如果它为空或空忽略它。目前查询如下…

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      

但我想找个伴。OfferText如果列表。Offertext是一个空字符串,如果它是null。

最好的解决方案是什么?


当前回答

我认为:

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

是最优雅的解决方案。

然后把它分解成伪代码:

// 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;

其他回答

[Column_name] IS NULL OR LEN(RTRIM(LTRIM([Column_name]))) = 0

COALESCE和NULLIF的简单组合应该可以做到:

SELECT             
  Coalesce(NULLIF(listing.OfferText, ''), company.OfferText) As Offer_Text
...

注意:如果希望语句返回空字符串而不是NULL(如果两个值都为NULL),则添加另一个空字符串作为最后一个COALESCE参数。

这里有一个解决方案,但我不知道它是否是最好的....

Select              
Coalesce(Case When Len(listing.Offer_Text) = 0 Then Null Else listing.Offer_Text End, company.Offer_Text, '') As Offer_Text,         
from tbl_directorylisting listing  
 Inner Join tbl_companymaster company            
  On listing.company_id= company.company_id
Select              
CASE
    WHEN listing.OfferText is null or listing.OfferText = '' THEN company.OfferText
    ELSE COALESCE(Company.OfferText, '')
END As Offer_Text,         
from tbl_directorylisting listing  
 Inner Join tbl_companymaster company            
  On listing.company_id= company.company_id

我认为:

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

是最优雅的解决方案。

然后把它分解成伪代码:

// 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;