Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you optimize this code? T-SQL

Tags:

sql-server

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
like image 972
Matt Avatar asked Jan 23 '23 01:01

Matt


1 Answers

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)], ''))
like image 158
Andomar Avatar answered Jan 29 '23 13:01

Andomar