I have the following query:
INSERT INTO major (key_1, key_2, ... , key_N)
VALUES (v_1_1, v_1_2, v_1_3, ... , c_1_N)
(v_2_1, v_2_2, v_2_3, ... , c_2_N)
...
(v_K_1, v_K_2, v_K_3, ... , c_K_N)
where key_i
is name of column, and v_i_j
is random value from 1
to L
. N
,L
and K
are positive integers (our input).
I am going to write mysql procedure that create random (with values from 1
to L
) matrices* (K
xN
) and place it to database using query presented above.
Now It is realised by code in php
and doctrine
but I want to achieve the same result in pure SQL procedure that as input gets (N
,L
,K
). Theres is php
code:
$conn = DriverManager::getConnection($connectionParams);
$conn->beginTransaction();
try {
for ($i = 1; $i <= $k; $i++) { // row in table major
$content=[];
for ($j = 1; $j <= $n; $j++) { // foreign key of row
$content['key_' . $j] = rand(1, $l);
}
$conn->insert('major', $content);
}
$conn->commit();
} catch(\Exception $e) {
$conn->rollBack();
throw $e;
}
*I wrote matrices
but I know that without order of rows it is not matrix in strict sense.
So I do not want to make query inside loop, but loop inside query. I know it is bad practice, but I am thinking about concatenating and evaluating query inside of procedure? It is possible? Or is these better solution?
Best Answer
I solved this writhing the following code:
And this can be used (for N=20,L=25,K=3) by command:
Sources:
Loops in MySQL
Execution of text variable as query