Home > OS >  MySQL If variable equals then execute query
MySQL If variable equals then execute query

Time:09-29

I have a requirement in MySQL 5.7 to only run a query if a condition is true.

For example, below we have a variable called x. If it equals 8, we're OK to run the query.

I'm trying to use an IF statement for this

Can anyone tell me what's going wrong?

Thanks

SET @x = (select count(*) from (select distinct tbl  from db.tbl where dt = CURDATE())x);
    
IF @x = 8
   BEGIN
       SELECT * from db.tbl1
   END

CodePudding user response:

You don't need a procedure. Plain SQL will do:

SELECT * from db.tbl1
WHERE (select count(distinct col) from db.tbl where dt = CURDATE()) = 8

Note also the simplification using count(distinct ...)

  • Related