PlusMagi's Blog By Pitt Phunsanit Automation,SQL Scripting Batch Execute All SQL Files in Folder for MSSQL

Batch Execute All SQL Files in Folder for MSSQL

Executing multiple SQL files manually can be time-consuming, especially when dealing with a large number of scripts. This article provides a PowerShell script that automates the process of executing all SQL files in a specified folder against a target MSSQL database. By using the script, you can streamline your workflow and save time.

Configuration Section

Before running the script, you need to configure the following variables:

  • $SqlServerName: The name of your SQL Server instance. For example, LOCALHOST or SQLDEVINSTANCE1.
  • $DatabaseNameTarget: The name of the target database where the SQL scripts will be executed.
  • $SCRIPT_PATH: The path to the folder containing your SQL scripts. The script attempts to find the path of the first .sql file, otherwise, it defaults to the current directory.

Execution Section

The script starts by displaying the server, database, and script path. It then finds all .sql files in the specified folder and sorts them by name to ensure that numbered files are executed in the correct order. For each file, the script executes it using the sqlcmd utility with Windows Authentication. The script captures and displays the output, including row counts from INSERT/UPDATE/DELETE operations.

Error Handling

If an error occurs during the execution of a SQL file, the script stops immediately and displays the error output. This helps you quickly identify and resolve issues.

Conclusion

The provided PowerShell script simplifies the process of executing multiple SQL files in a folder against a target MSSQL database. By automating this task, you can save time and reduce the risk of errors. Make sure to configure the script variables according to your environment before running it.