Skip to content
Advertisement

Invalid syntax error near ‘<' when using case when variable, works fine without variable

I am trying to resolve this SQL issue where my code throws an error

Invalid syntax error near ‘<‘

when I use the variable @totalprice. Without using the variable, the CASE works and the query executes correctly but I want it as a variable

Thanks

Declare @totalprice int
Select 
Case @totalprice
      when "Age" < 2 THEN [Price(RM)]+100 
      when "Age" > 2 AND "Age" <= 11 THEN [Price(RM)]+200
      when "Age" > 11 AND "Age" <= 17 THEN [Price(RM)]+300
      when "Age" > 17 AND "Age" <= 64 THEN [Price(RM)]+500
      when "Age" >= 65 THEN [Price(RM)]+200
END AS Total_Price
From Reservation

Advertisement

Answer

If you want to assign the result of the CASE expression to your variable – use this code:

DECLARE @totalprice int

SELECT
    @totalprice = CASE
                     WHEN Age < 2 THEN [Price(RM)] + 100 
                     WHEN Age > 2 AND Age <= 11 THEN [Price(RM)] + 200
                     WHEN Age > 11 AND Age <= 17 THEN [Price(RM)] + 300
                     WHEN Age > 17 AND Age <= 64 THEN [Price(RM)] + 500
                     WHEN Age >= 65 THEN [Price(RM)] + 200
                  END 
FROM
    Reservation
```
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement