mysql: Can I use an Case Expression to execute other statements?

SET @Count = '2'; SELECT CASE @Count  WHEN 1 THEN INSERT INTO customer (First_Name) VALUES (John)   WHEN 2 THEN INSERT INTO customer (First_Name) VALUES (Mary)  ELSE INSERT INTO customer (First_Name) VALUES (Ray)  END; 

–this is a mysql case expression. Can I use it to execute other mysql statements like this? Actually want to execute a block of statements depending on the value of @count

Add Comment
1 Answer(s)

You can move the logic within a single statement:

insert into customer(firstname) select case @Count     when 1 then 'John'     when 2 then 'Mary'     else 'Ray' end 

Alternatively, you want a case statement rather than a case expression:

case @Count     when 1 then insert into customer(firstname) values('John');     when 2 then insert into customer(firstname) values('Mary');     else insert into customer(firstname) values('Ray'); end case; 
Answered on September 1, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.