Monday, September 24, 2007

SQLCMD -- Part II (Interactive Mode)

First get connected into the DB Server using SQLCMD using either the windows authentication or SQL authentication as explained in the previous post.

Then on the prompt you can type in the TSQL queries directly and press enter. In the next line, say Go and press enter to execute the query and see the result. See below an example to display the current datetime.


After displaying the result the cursor would stand on the prompt expecting for further queries from us :) Once you are done you can 'exit' out of sqlcmd utility like shown below:


By default, it get's connected to the default database of that login only. One can make use of -d switch to connect to a DB of their choice. Please refer the below sample where I make use of Adventureworks DB and query a table.


What is the difference between -q and -Q switch?

-q is for running queries from SQLCMD.
-Q is for exitting from SQLCMD immediately after executing a given query.

SQLCMD -q "Select getdate()"

This query will print the current datetime and then return to SQLCMD prompt.

SQLCMD -Q "Select getdate()"

This query will print the current datetime and then exit from SQLCMD automatically.

No comments: