SQL SERVER – Execute Operating System Commands in sqlcmd

Here is the email received just the other day -

“Hi Pinal,

I have been using sqlcmd for a long time and I find it very comfortable. I am going to soon learn Powershell as well.

However, here is one typical problem I face it every day and I want to check if you have any workaround.

When I work with sqlcmd I always connect via command prompt and whenever I want to check something back in OS, I always have to exit from sqlcmd or I have to open different window.

Is there any trick, which I can use to execute Operating System commands while I am still in sqlcmd prompt?

Thanks!”

Indeed a great question, as in my early career I had faced the same issue and I finally figured out the solution.

While we are in the sqlcmd mode at that time we can use !! (Double exclamation marks) to execute Operating System Commands.

Here is the example how you can do the same with the help of command prompt:

Here is the example how you can do the same with the help of SSMS:

First go to SSMS >> Menu >> Query >> SQLCMD mode

Once you enable SQLCMD mode in SSMS you can now execute any SQLCMD command in SSMS New Query Windows. You can also execute OS commands in this window.

If you know any such tricks, please leave a comment and I will publish on the blog with due credit.

Reference: Pinal Dave (http://blog.sqlauthority.com)

One thought on “SQL SERVER – Execute Operating System Commands in sqlcmd

  1. Hi Pinal,

    This is really cool tips, I am enjoying to read your blog and learn new stuff. Is there any way to use output of OS command in query? l mean If I use dir command and I want to use out put of that command into further query. Thanks.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s