Run SQL files inside subdirectories on Linux

0

I have a repository of SQL files where each represents a stored procedure . These files are inside a directory organized in other subdirectories.

Example of my directory structure:

stored-procedures
---d1
------sd1
---------sp1.sql
---------sp2.sql
---------sp3.sql
------sd2
---------sp4.sql
---------sp5.sql
------sd3
---d2
------sd4
---------sp6.sql
---d3
------sd5
------sd6

The command I use to execute each stored-procedure separately is as follows:

mysql -uuser -psenha bd < sp1.sql --force

How can I do this on Linux through the command line or creating a script ?

    
asked by anonymous 14.11.2014 / 11:38

2 answers

1

I was able to build my own script as follows:

#!/bin/bash
shopt -s globstar
echo '...'

if [ $# -lt 2 ]
then
    echo "Favor definir dois parâmetros para execução deste script"
    echo "Primeiro parâmetro:"
    echo "      nome do usuário do banco de dados"
    echo "Segundo parâmetro:"
    echo "      senha do usuário do banco de dados"
    echo "Execução interrompida"
    echo '...'
    exit 1
fi

echo "Iniciando a execução das stored-procedures no diretório /var/www/stored-procedures"
for file in /var/www/stored-procedures/**/*.sql
do
    echo $file
    mysql -u$1 -p$2 banco_de_dados < $file --force  
done
echo "Execução do script finalizada"
echo '...'

Note 1: As a parameter, the user must pass the user and password of the database containing the stored procedures.

Note 2: The directory used was /var/www/stored-procedures , but simply change this code snippet to your directory containing stored procedures.

    
14.11.2014 / 14:47
0

Assuming your directory tree is something like:

$ tree stored-procedures/
stored-procedures/
|-- d1
|   |-- sd1
|   |   |-- sp1.sql
|   |   |-- sp2.sql
|   |   '-- sp3.sql
|   |-- sd2
|   |   |-- sp4.sql
|   |   '-- sp5.sql
|   '-- sd3
|-- d2
|   '-- sd4
|       '-- sp6.sql
'-- d3
    |-- sd5
    '-- sd6

15 directories, 0 files

You can use the find utility to solve your problem:

$ find ./stored-procedures/ -name "*.sql" -exec mysql -uuser -psenha bd -e \"source {}\" \;
    
11.05.2018 / 17:09