Lain
Lain

Reputation: 2216

Run all .sql files in directory on linux with SQL server

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.

Upvotes: 1

Views: 3789

Answers (2)

7 Reeds
7 Reeds

Reputation: 2539

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.

Upvotes: 2

Lacobus
Lacobus

Reputation: 1658

find to the rescue:

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

Upvotes: 0

Related Questions