rahman
rahman

Reputation: 4948

mysql script variables and max function

The question is fairly simple. I just couldn't locate the solution so I'm asking, Here is the contents of a *.sql file:

select @max_command_idx=max(command_idx)+1  from command;
insert into command values(3,0,@max_command_idx+1 ,"sub","ctrlr",1,0,"plan",0);
insert into command values(4,1,@max_command_idx+1 ,"sub","ctrlr",1,0,"pla1n",0);

when i executed the script, i expected @max_command_idx to be a fixed value.which means it should substitute "same" value in both of the subsequent insert statements. But it didn't do that. what it did was to give me new value of max_command_idx for each insert statement. why is that? and how may i solve it? Thank you

Upvotes: 0

Views: 169

Answers (1)

Tom Mac
Tom Mac

Reputation: 9853

The first row will set @max_command_idx to be null since you are actually selecting a boolean condition. So when running this:

select @max_command_idx=max(command_idx)+1  from command;

You are actually saying "select me 1 if @max_command_idx is equal to the current maximum command_idx + 1, select me 0 if it is not and select me null if @max_command_idx is null".

In your case @max_command_idx is null so the boolean result is null hence it appears as if @max_command_idx is re-initialised in each of the subsequent inserts.

Try this:

select max(command_idx)+1 into @max_command_idx  from command;
insert into command values(3,0,@max_command_idx+1 ,"sub","ctrlr",1,0,"plan",0);
insert into command values(4,1,@max_command_idx+1 ,"sub","ctrlr",1,0,"pla1n",0);

Should do what you want...

Upvotes: 1

Related Questions