Lesson 2: Running Transact-SQL Script Files by Using sqlcmd
After you use sqlcmd to connect to a named instance of Microsoft SQL Server, the next step is to create 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:
Click Start, point to All Programs, point to Accessories, and then click Notepad.
Copy and paste the following Transact-SQL code into Notepad:
USE AdventureWorks GO SELECT c.FirstName + ' ' + c.LastName AS 'Employee Name', a.AddressLine1, a.AddressLine2 , a.City, a.PostalCode FROM Person.Contact AS c INNER JOIN HumanResources.Employee AS e ON c.ContactID = e.ContactID INNER JOIN HumanResources.EmployeeAddress ea ON ea.EmployeeID = e.EmployeeID INNER JOIN Person.Address AS a ON a.AddressID = ea.AddressID GO
Save the file as myScript.sql in the C drive.
Open a command prompt window.
In the Command Prompt window, type: sqlcmd -S myServer\instanceName -i C:\myScript.sql -o C:\EmpAdds.txt
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.
For more information, see sqlcmd Utility.