skip to Main Content

I have an sql query on which I want to pass a param value and get the result but I am not able to achieve this.

SELECT  
CASE
    WHEN x>0 and x<=5 THEN  1
    WHEN x>5 and x<=10 THEN 2
    WHEN x>10 and x<=15 THEN 3
    WHEN x>15 and x<=35 THEN 4
    WHEN x>35 THEN 6
END

I want to pass value of x in above query and get the result.
Eg:
x = 7
result = 2

2

Answers


  1. If you are using MySQL you can use SET command: SET @x = 7;
    Once you declared it you can use it in your query, something like this:

    CASE
        WHEN @x>5 and @x<=10 THEN 2
    

    https://dev.mysql.com/doc/refman/8.0/en/user-variables.html

    Login or Signup to reply.
  2. Use set @yourvarname=yourvarvalue then add @ to the parametrized variable, in your case @x

    set @x=10;
    SELECT  
    CASE
        WHEN @x>0 and @x<=5 THEN  1
        WHEN @x>5 and @x<=10 THEN 2
        WHEN @x>10 and @x<=15 THEN 3
        WHEN @x>15 and @x<=35 THEN 4
        WHEN @x>35 THEN 6
    END
    

    Sql fiddle

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search