1

I have seen this question for windows: Run all SQL files in a directory

I was wondering how to do it for linux. To my knowledge .bat filetype is for windows. Anyone know a simple script for linux? I rarely use linux.

I have code to run them one at a time with

sqlcmd -S localhost -U SA -p myPassword -i myFile1.sql

(My sql files have which database to use). Just unsure how to make it run for all them since there are a lot.

2 Answers 2

2

A very simplistic sh script file might contain:

#!/bin/sh

#
# loop over the result of 'ls -1 *.sql'
#     'ls -1' sorts the file names based on the current locale 
#     and presents them in a single column
for i in `/bin/ls -1 *.sql`; do 
    sqlcmd -S localhost -U SA -p myPassword -i $i
done

If there is a specific order to the sql files then you would need to name them in a way that sorts into the correct order.

Sign up to request clarification or add additional context in comments.

9 Comments

Do I just save this as like myScript.sh in the same directory as the .SQL files and run it via terminal?
yes -- you save it to a file in that dir and then either: 1) /bin/sh myScript.sh or 2) ` chmod 754 myScript.sh; ./myScript.sh. The first version uses the sh` interpreter to run the script file and the second version makes the script file executable.
Thats what I did. However I got "Sqlcmd: 'myPassword': unexpected argument. Argument Value as to be one. " a crap ton of times (Assume for every file).
My first thought is: if your password has spaces or special characters in it make sure you surround it with single quotes. You could run into similar issues if your sql files have spaces or "shell special" characters in the names
Why would you write for i in `/bin/ls -1 *.sql`; when you could just write for i in *.sql; which is more efficient and works reliably for filenames containing whitespace.
|
0

find to the rescue:

find ./directory -maxdepth 1 -name *.sql -exec sqlcmd -S localhost -U SA -p myPassword -i {} \;

1 Comment

getting following Error: find: sqlcmd: No such file or directory

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.