0

i would like to make SELECT statement when the condition is equals to 1, so that will execute INSERT statement, when not, so it will not doing anything. What i think you can see below in my code.

SET @var = 1;

SELECT IF(@var = 1, 
    INSERT INTO tabulka VALUES('value1','name1'),
    0
)

Thanks

Bushwacka
  • 865
  • 4
  • 12
  • 22
  • the condition or the number 3... is this a parameter you're passing in or is it something in another table or...? – gloomy.penguin Nov 02 '13 at 19:49
  • Is *condition* a function a row data? – PM 77-1 Nov 02 '13 at 19:54
  • Ït is only example. I have more difficult query than this, but what i really need is when the variable is equals to 1 so that will execute 'Insert' statement. I don't know if i need 'if' condition. – Bushwacka Nov 02 '13 at 19:54
  • See if answers to [this SO question](http://stackoverflow.com/questions/485039/mysql-insert-where-query) help any. – PM 77-1 Nov 02 '13 at 19:56
  • [this answer](http://stackoverflow.com/a/15766493/623952) explains that mysql only recognizes `if` when it is between a `begin` and `end` for a stored procedure (or trigger)... maybe there is another way to do what you want to do. could you try explaining the whole situation? are you using PHP at all? is a stored procedure an option for you? – gloomy.penguin Nov 02 '13 at 20:59

2 Answers2

1

You just need an IF statement, not a SELECT.

if
    @var = 1
then
    insert into tabulka values('value1', 'name1');
end if
jokeeffe
  • 395
  • 1
  • 6
0

got it!

http://sqlfiddle.com/#!2/66b33/1/0

create table test (
    int_field int, 
    str_field varchar(10) 
  );


set @var := 1;

insert into test 
   select  int_field, str_field 
   from    (select @var as int_field,
                   concat('var=',@var) as str_field 
           ) as temp
   where   @var=3;


set @var := 3;

insert into test 
   select  int_field, str_field 
   from    (select @var as int_field,
                   concat('var=',@var) as str_field 
           ) as temp
   where   @var=3; 


select * from test; 

results in:

int_field      str_field
3              var=3
gloomy.penguin
  • 5,833
  • 6
  • 33
  • 59