March 17, 2015

Batch execution of SQL Files using SQLCMD

Did you ever have the need to execute multiple SQL Scripts in a (sub)directory? Reasons for this could be…

  • Automated Checks like consistency
  • Pre- or Post-Deployment Scripts
  • Dynamic Frameworks
  • And so on…

You could execute them one by one by hand, using a main script or – what I prefer as a lazy guy – dynamically invoke them. I used SQLCMD to realize this.

Here’s a way to do it via a DOS Batch file – not my preferred solution but sometimes you need to use DOS batches due security restrictions and stuff…

More or less the same could be done using PowerShell – But there you have more possibilities like formatting the result of queries. The following script saves the results in a regular text file AND in a CSV file – just to mention one of many possibilities.

1 Comment

  1. Reply


    September 18, 2015

    I have a question on your explame to deploy a SQL Script to multiple machines with just 4 lines of PowerShell solution. I am trying to build something similar in Powershell. However, I can't figure out how to capture the error from SQL Server if there is one when using invoke-sqlcmd . For explame, if I am deploying a stored procedure and the stored procedure already exists in that database, I want to see the erorr There is already an object named in the database. in the results window. Can I do that?Thanks,Laura

Would you like to share your thoughts?

Would you like to share your thoughts?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.