tags:

views:

866

answers:

2

Is there a way in a mysql script to declare an array(or any collection) and looping over it for doing stuff.

Ex :

SET @myArrayOfValue=[2,5,2,23,6]


for each @value in @myArrayOfValue
   INSERT INTO EXEMPLE VALUES(@value, 'hello');
end for each

Thanx in advance.

A: 

No, SQL does not support FOR EACH/etc syntax. The closest you'd get would be to use cursors. Also, there is no array syntax in SQL - you'd have to use:

SELECT 2 FROM DUAL
UNION ALL
SELECT 34 FROM DUAL
UNION ALL 
SELECT 24 FROM DUAL

... to construct your "array of values" equivalent in SQL.

SQL scripts would have individual INSERT statements. You'd be looking at using PHP/Java/etc. to use FOR loop-esque syntax like what is provided in your example.

OMG Ponies
I don't mind to use a cursor, but values need to come from something like this SET @myValues [2,34,22].Thanx
Mike
Thanx, it's what I was looking for. The syntax is too ugly to use but it anwsered my question.
Mike
A: 

Could you use something like MySQL SET? instead of looping through you could store the values in a SET.

Phill Pafford
No I can't, I need to insert values in different rows. I want to do this to have a script easy to use.
Mike
Use PHP (or something) and loop through each of the array and just do a simple insert then
Phill Pafford
I need it in a mySQL script.
Mike
what format does the values come in? CSV, in a text file, etc...?
Phill Pafford
The come from user edit at the beginning of the script. So it's in mysql format.
Mike