Condition for INSERT INTO

2

I need SQL to check if there is any value equal to 1, 2 or 3 in the '@variavel' sent; If it is green enter the value 1, otherwise enter the value 0.

Note: the table and column can be given as example as fictitious.

    
asked by anonymous 24.10.2018 / 14:16

2 answers

5

Basically this:

INSERT INTO tabela SET coluna = IF( @variavel IN (1,2,3), 1, 0 );
  • The IN returns true if the variable is in the list

  • The IF returns the second value if the first expression is true, otherwise it returns the third.

See working in SQL Fiddle .


Notes:

24.10.2018 / 14:22
3

Using SQL Ansi, which works across all databases, you can do something like:

insert into dados (coluna1) values (
case @parametro 
   when 1 then 1
   when 2 then 1
   when 3 then 1
   else 0
end)
    
24.10.2018 / 14:25