Skip to content
Advertisement

How to use case to construct a conditional update

I have to write an update query. If the special_member account is not cancelled then in the where clause I have to use this condition by adding a grace period of 15 days to the expiry date and compare it today’s date:

If the membership is cancelled then I have to compare the actual expiry date with today’s date. This is my full query:

When I execute it I am getting:

Incorrect syntax near ‘>’.

Advertisement

Answer

Its a case expression, not a statement, as as such it can only return a value i.e. cannot contain any conditions. Just move the value you are comparing to outside the case e.g.

That however is not sargable i.e. cannot make use of any indexes on MEMBER_EXPIRY_DATE so I would recommend switching the logic around to

Notes:

  • Dates don’t naturally add, use the dateadd function.
  • There is nothing dynamic about this – dynamic SQL is something quite different
  • Using a good layout and consistent casing makes a big difference in being able to read your SQL
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement