Friday, April 15, 2011

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

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?

From stackoverflow
  • SELECT
       CASE WHEN LEN(listing.OfferText) > 0 THEN listing.OfferText 
            ELSE COALESCE(Company.OfferText, '') END 
       AS Offer_Text,
    
    ...
    

    In this example, if listing.OfferText is NULL, the LEN() function should also return NULL, but that's still not > 0.

  • 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
    
  • You can use ISNULL and check the answer against the known output:

    SELECT case when ISNULL(col1, '') = '' then '' else col1 END AS COL1 FROM TEST

  • Here's a solution, but I don't know if it's the best....

    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
    
  • Here is another solution:

    SELECT Isnull(Nullif(listing.offertext, ''), company.offertext) AS offer_text, 
    FROM   tbl_directorylisting listing 
           INNER JOIN tbl_companymaster company 
             ON listing.company_id = company.company_id
    
  • I think this:

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

    is the most elegant solution.

0 comments:

Post a Comment