tags:

views:

58

answers:

2

Essentially I have three fields and I am creating a new one which is the three combined making a mailable address; problem being some fields contain null values and adding myString to a null just produces a null in sql.

So this is my code, can anyone make it any cleaner? It's still looking pretty butch!

  UPDATE [mydb].[dbo].[Account]
  SET [Billing Street] = CASE
  WHEN [(Billing Address 1)] is null and [(Billing Address 2)] is null THEN [(Billing Address 3)]
  WHEN [(Billing Address 1)] is null and [(Billing Address 3)] is null THEN [(Billing Address 2)]
  WHEN [(Billing Address 2)] is null and [(Billing Address 3)] is null THEN [(Billing Address 1)]
  WHEN [(Billing Address 1)] is null THEN [(Billing Address 2)] + ' ' + [(Billing Address 3)]
  WHEN [(Billing Address 2)] is null THEN [(Billing Address 1)] + ' ' + [(Billing Address 3)]
  WHEN [(Billing Address 3)] is null THEN [(Billing Address 1)] + ' ' + [(Billing Address 2)]
  ELSE [(Billing Address 1)] + ' ' + [(Billing Address 2)] + ' ' + [(Billing Address 3)]
  END
+7  A: 

You could use isnull and ltrim to remove any leading whitespace:

update [mydb].[dbo].[Account]
set [Billing Street] = ltrim(isnull([(Billing Address 1)], '') +
                       isnull(' ' + [(Billing Address 2)], '') +
                       isnull(' ' + [(Billing Address 3)], ''))
Andomar
+1 - deleted mine which was essentially the same, just using coalesce.
AdaTheDev
Nice work! The braket after the first parameter of the last isnull tripped me up breifly, but thats sweet as a nut, thank you :)
Yoda
+2  A: 

If both old and new columns are going to coexist, you'd be better creating a computed column - that way, they never get "out of sync" with each other.

Take Andomars statement, and change it to read:

ALTER TABLE Account ADD
  [Billing Street] AS LTRIM...

Where LTRIM... continues as in Andomar's answer

Damien_The_Unbeliever