SQLCMD is a command line query tool shipped with SQL Server 2005. If you need to run a batch file to call a query or procedure, and then retrieve the output in a file, then it’s a very useful tool to use.
Basic syntax can be found in http://msdn2.microsoft.com/en-us/library/ms162773.aspx but let me show you few example of how to use it.
Find out the available parameters available to use:
C:\sqlcmd -?
By the way, keep in mind that all parameters pass in are CASE SENSITIVE!
To run in an interactive mode by passing login information and then you can type in sql query and see the result like how you use oracle sqlplus. Use -S for server name, -d for database name, -U for DB user name, -P for password:
C:\sqlcmd -S YourServerName -d YourDBName -U DbUserName -P password
1> select first_name from Users
2>go
first_name
---------------
Jane Doe
John Smith(2 rows affected)
1> exit
C:\
With trusted connection to run a query and save output into a text file; -E for trusted connection, -o for output file name:
C:\sqlcmd -E -S YourServerName -d YourDBName -q "select count(*) from Users" -o C:\output1.txt
To get rid of the header, pass in “-h -1″:
C:\sqlcmd -E -S YourServerName -d YourDBName -q "select count(*) from Users" -o C:\output1.txt -h -1
To pass in an sql script file and generate output; -i for input file:
C:\sqlcmd -E -S YourServerName -d YourDBName -i user_data.sql -o C:\output1.txt
Enjoy and hope this help!
Tracy