Condition for INSERT INTO

Asked

Viewed 224 times

2

I need SQL to check that in the '@variable' sent there is a value equal to 1, 2 or 3; If true enter the value 1, otherwise enter the value 0.

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

  • 1

    What database is that? SQL itself does not accept this by default, but language extensions of a database can accept, probably should be in a stored Procedure.

  • Just like your script INSERT

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, or returns the third.

See working on SQL Fiddle.


Notes:

3

Using SQL Ansi, which works on 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)

Browser other questions tagged

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