SQL Computed Values

Lets say I would like to query a table but I would like to compute a column according to another value.

Example:

Original Table Columns:

  • Id (int)
  • FirstName (varchar)
  • LastName (varchar)
  • Married (bit)
  • FamilyName (varchar)

I would like to get from table “Females” the following data, where Last Name should have the original nee surname if married:

  • Id
  • FirstName
  • LastName

Sql Statement: 

SELECT Id, First Name, (CASE WHEN Married = ‘1’ THEN LastName + ‘ Nee ‘ + FamilyName ELSE LastName END) As LastName FROM Females

 

Result would look like:

Id First Name Last Name
1  Jane  Smith
2  Sue  Duffy Nee Perry
3  Kelly  Johnson Nee Smith
4  Marie  Dickson

Where 1 and 4 have Married as False, while 2 and 3 have Married as True

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s