Friday, March 29, 2013

Executing SQL Script from Command Line

Yes, It's more pretty your SQL Server Management Studio, because you can just go to "File" option, find there "Open" and click on "File..." to load a SQL file (.sql) to execute it without problems.

But, have you ever tried to do so with a file create by this tool being large enough to freeze it literally when you open it? Well, in this case there's no way to execute that file through the tool.

Therefore, here we are with a SQL Server command that will help us with this task. You just have to keep in mind the command: sqlcmd, simple right?.

Let's say that we have a SQL server called "MY_SERVER" and my SQL instance "MY_INSTANCE" installed there. What I need now is to execute the following script "my_large_script.sql" located at "D:\Test".

It's important to consider that this command use Windows authentication by default, so it's only required to put this line in any command prompt:

sqlcmd -S MY_SERVER\MY_INSTANCE  -i D:\Test\my_large_script.sql

However, if you are using SQL authentication it's neccesary to use your credential in this way:

sqlcmd -S MY_SERVER\MY_INSTANCE  -U domain\my_user -P my_password -i D:\Test\my_large_script.sql

That's all, have fun with your scripts.




3 comments: