NULLs propagate through expressions

NULLs propagate through expressions

This is extremely simple but haven't found anyone that can answer. Let's say I concatenate two columns, LName + FName, to create column Membname. There is a LName but the FName exists only some of the time. For all of the values without a FName, the new column populates as NULL. How can I get the FName and LName, or LName only if the FName does not exist? I tried writing an IF statement to no avail. Must I create a stored procedure?

    Requires Free Membership to View

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

Use the COALESCE function. If LName will never be NULL, you'd need to use it only on the Fname column.

select LName 
     + coalesce( ', ' + Fname, '' ) 
          as Membname
  from yourtable

Note here how Fname is first concatenated to a string consisting of a comma followed by a space. Now since NULLs propagate through expressions, therefore if Fname is NULL, then the concatenation of ', ' and Fname will also be NULL, and thus, the COALESCE function will return a zero-length or empty string. Otherwise, the concatenation of ', ' and Fname will be concatenated to Lname.

The net effect is that Membname will be either Lname only, or Lname followed by a comma and space and then Fname. Sweet, eh?


This was first published in March 2005

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.