How to use If with Insert in MySQL?

0

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

It's relatively simple, but I can not seem to find it because in most forums people embellish so much the codes that I get lost. I want something straight.

    
asked by anonymous 06.03.2018 / 17:46

1 answer

1

I do not know if it's the ideal solution. I also do not know if it's the right way. 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 it like this:

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

In PHP it's a bit simpler, but since it did not indicate any language, I do not know if it's using any.

if($x>10){
   $sql = "insert into tabela(campos) values(valores)";
}else{
   $sql = "select campos from tabela";
}
    
06.03.2018 / 18:44