-1

I wanted to have a following update query using nested case;

UPDATE mstsales 
SET test = '2017-18'
WHERE salemonth > 3 AND saleyear = 2017 OR salemonth < 4 AND saleyear = 2018  

UPDATE mstsales 
SET test = '2018-19'
WHERE salemonth > 3 AND saleyear = 2018 OR salemonth < 4 AND saleyear = 2019  

UPDATE mstsales 
SET test = '2019-20'
WHERE salemonth > 3 AND saleyear = 2019 OR salemonth < 4 AND saleyear = 2020  
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

1

You can do:

UPDATE mstsales 
    SET test = (CASE WHEN salemonth > 3 and saleyear = 2017 or salemonth < 4 and saleyear = 2018 THEN '2017-18'
                     WHEN salemonth > 3 and saleyear = 2018 or salemonth < 4 and saleyear = 2019  THEN '2018-19'
                     WHEN salemonth > 3 and saleyear = 2019 or salemonth < 4 and saleyear = 2020 
                END)
WHERE (salemonth > 3 and saleyear = 2017 or salemonth < 4 and saleyear = 2018) OR 
      (salemonth > 3 and saleyear = 2018 or salemonth < 4 and saleyear = 2019) OR
      (salemonth > 3 and saleyear = 2019 or salemonth < 4 and saleyear = 2020)

I don't think this simplifies the logic.

You don't mention your database. But there are cleaner alternatives:

  • Use a computed column.
  • Use a reference table.
  • Use a derived table for the update.
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Hope this helps..

UPDATE mstsales
SET     test =  CASE  
                        WHEN salemonth > 3 and saleyear = 2017 or salemonth < 4 and saleyear = 2018  THEN '2017-18' 
                        WHEN salemonth > 3 and saleyear = 2018 or salemonth < 4 and saleyear = 2019  THEN '2018-19' 
                        WHEN salemonth > 3 and saleyear = 2019 or salemonth < 4 and saleyear = 2020  THEN '2019-20' 
                    END 

If there is common condition for all the cases, move into where clause.