Friday, September 2, 2011

Running Transact-SQL Script Files by command line - sqlcmd


You can use sqlcmd to run a Transact-SQL script file. A Transact-SQL script file is a text file that can
contain a combination of Transact-SQL statements, sqlcmd commands, and scripting variables.
To create a simple Transact-SQL script file by using Notepad, follow these steps:

1.  Click Start, point to All Programs, point to Accessories, and then click Notepad.
2.  Copy and paste the following Transact-SQL code into Notepad:
     USE AdventureWorks2008R2;
     GO
     Select Emp.Address from EMP
    Where ID = 1
    GO
3.      Save the file as myScript.sql in the C drive.
To run the script file

1. Open a command prompt window.
2. In the Command Prompt window, type:

sqlcmd -S .\SQLExpress -i C:\myScript.sql

3. Press ENTER.
A list of Adventure Works employee names and addresses is written to the command prompt window.
To save this output to a text file

1. Open a command prompt window.
2.  In the Command Prompt window, type:

sqlcmd -S myServer\instanceName -i C:\myScript.sql -o C:\EmpAdds.txt

3.  Press ENTER.
No output is returned in the Command Prompt window. Instead, the output is sent to the EmpAdds.txt file.
You can verify this output by opening the EmpAdds.txt file.

No comments :

Post a Comment