How to use If with Insert in Mysql?

Asked

Viewed 995 times

0

I have a variable x, and I want to check its value with an if, and if the value is above 10 (for example) I want to perform an Insert in a table, otherwise a select in it.

It’s something relatively simple, but I can’t find it because in most forums people embellish the codes so much that I end up getting lost. I want something direct.

1 answer

1

I don’t know if it’s the ideal solution.
I don’t know if it’s the right way either.
But for the title of curiosity and study (for me and for everyone), take a look at this Function.

DELIMITER //

CREATE FUNCTION SimpleCompare(n INT)
  RETURNS VARCHAR(500)

  BEGIN
    DECLARE s VARCHAR(500);

    IF n <= 10 THEN insert into tabela(campo) values(FLOOR(RAND()*10)); SET s = 'INSERIDO';
    ELSE select GROUP_CONCAT(campo) from tabela into s;
    END IF;

    RETURN s;
  END //

DELIMITER ;

Calling her that:

select SimpleCompare(8);
select SimpleCompare(11);

In PHP it is a little simpler, but as no language indicated do not know if you are using any.

if($x>10){
   $sql = "insert into tabela(campos) values(valores)";
}else{
   $sql = "select campos from tabela";
}
  • 2

    IS function and not procedure. Another solution to the select is to create a cursor and iterate on it if you need something more complex.

  • Function, Edited ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.