Sqlcommand 2005
Sqlcommand 2005
sqlcmd Utility
SQL Server 2005
The sqlcmd utility lets you enter Transact-SQL statements, system procedures, and script files at
the command prompt, in Query Editor in SQLCMD mode, in a Windows script file or in an
operating system (Cmd.exe) job step of a SQL Server Agent job. This utility uses OLE DB to
execute Transact-SQL batches.
Important:
SQL Server Management Studio uses the Microsoft .NET Framework SqlClient for execution in
regular and SQLCMD mode in Query Editor. When sqlcmd is run from the command line,
sqlcmd uses the OLE DB provider. Because different default options may apply, you might see
different behavior when you execute the same query in SQL Server Management Studio in
SQLCMD Mode and in the sqlcmd utility.
Syntax
sqlcmd
[{ { ‐U login_id [ ‐P password ] } | –E trusted connection }]
[ ‐z new password ] [ ‐Z new password and exit]
[ ‐S server_name [ \ instance_name ] ] [ ‐H wksta_name ] [ ‐d db_name ]
[ ‐l login time_out ] [ ‐A dedicated admin connection ]
[ ‐i input_file ] [ ‐o output_file ]
[ ‐f < codepage > | i: < codepage > [ < , o: < codepage > ] ]
[ ‐u unicode output ] [ ‐r [ 0 | 1 ] msgs to stderr ]
[ ‐R use client regional settings ]
[ ‐q "cmdline query" ] [ ‐Q "cmdline query" and exit ]
[ ‐e echo input ] [ ‐t query time_out ]
[ ‐I enable Quoted Identifiers ]
[ ‐v var = "value"...] [ ‐x disable variable substitution ]
[ ‐h headers ][ ‐s col_separator ] [ ‐w column_width ]
[ ‐W remove trailing spaces ]
[ ‐k [ 1 | 2 ] remove[replace] control characters ]
[ ‐y display_width ] [‐Y display_width ]
[ ‐b on error batch abort ] [ ‐V severitylevel ] [ ‐m error_level ]
[ ‐a packet_size ][ ‐c cmd_end ]
[ ‐L [ c ] list servers[clean output] ]
[ ‐p [ 1 ] print statistics[colon format] ]
[ ‐X [ 1 ] ] disable commands, startup script, enviroment variables [and exit]
[ ‐? show syntax summary ]
Command-line Options
Login-Related Options
-U login_id
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 2 of 21
Note:
If neither the -U option nor the -P option is specified, sqlcmd tries to connect by using
Microsoft Windows Authentication mode. Authentication is based on the Windows account
of the user who is running sqlcmd.
If the -U option is used with the -E option (described later in this topic), an error message
is generated. If the –U option is followed by more than one argument, an error message is
generated and the program exits.
-P password
Is a user-specified password. Passwords are case sensitive. If the -U option is used and the
-P option is not used, and the SQLCMDPASSWORD environment variable has not been set,
sqlcmd prompts the user for a password. If the -P option is used at the end of the
command prompt without a password sqlcmd uses the default password (NULL).
Security Note:
Do not use a blank password. Use a strong password. For more information, see Strong
Passwords1.
The password prompt is displayed by printing the password prompt to the console, as
follows: Password:
User input is hidden. This means that nothing is displayed and the cursor stays in position.
The SQLCMDPASSWORD environment variable lets you set a default password for the
current session. Therefore, passwords do not have to be hard-coded into batch files.
The following example first sets the SQLCMDPASSWORD variable at the command prompt
and then accesses the sqlcmd utility. At the command prompt, type:
Security Note:
The password will be visible to anyone who can see your computer monitor.
sqlcmd
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 3 of 21
If the user name and password combination is incorrect, the OLE DB provider generates an
error message.
Note:
The OSQLPASSWORD environment variable has been kept for backward compatibility.
The SQLCMDPASSWORD environment variable takes precedence over the
OSQLPASSWORD environment variable; this means that sqlcmd and osql can be used
next to each other without interference and that old scripts will continue to work.
If the -P option is followed by more than one argument, an error message is generated and
the program exits.
-E trusted connection
Uses a trusted connection instead of using a user name and password to log on to SQL
Server. By default, without -E specified, sqlcmd uses the trusted connection option.
The -E option ignores possible user name and password environment variable settings such
as SQLCMDPASSWORD. If the -E option is used together with the -U option or the -P
option, an error message is generated.
-z new password
Change password:
-S server_name [ \instance_name ]
Specifies the instance of SQL Server to which to connect. It sets the sqlcmd scripting
variable SQLCMDSERVER.
Specify server_name to connect to the default instance of SQL Server on that server
computer. Specify server_name [ \instance_name ] to connect to a named instance of SQL
Server on that server computer. If no server computer is specified, sqlcmd connects to the
default instance of SQL Server on the local computer. This option is required when you
execute sqlcmd from a remote computer on the network.
If you do not specify a server_name [ \instance_name ] when you start sqlcmd, SQL
Server checks for and uses the SQLCMDSERVER environment variable.
Note:
The OSQLSERVER environment variable has been kept for backward compatibility. The
SQLCMDSERVER environment variable takes precedence over the OSQLSERVER
environment variable; this means that sqlcmd and osql can be used next to each other
without interference and that old scripts will continue to work.
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 4 of 21
-H wksta_name
-d db_name
Issues a USE db_name statement when you start sqlcmd. This option sets the sqlcmd
scripting variable SQLCMDDBNAME. This specifies the initial database. The default is your
login's default-database property. If the database does not exist, an error message is
generated and sqlcmd exits.
-l login time_out
Specifies the number of seconds before a sqlcmd login to the OLE DB provider times out
when you try to connect to a server. This option sets the sqlcmd scripting variable
SQLCMDLOGINTIMEOUT. The default time-out for login to sqlcmd is eight seconds. The
login time-out must be a number between 0 and 65534. If the value supplied is not
numeric or does not fall into that range, sqlcmd generates an error message. A value of 0
specifies time-out to be infinite.
Logs in to SQL Server with a Dedicated Administrator Connection (DAC). This kind of
connection is used to troubleshoot a server. This will only work with server computers that
support DAC. If DAC is not available, sqlcmd generates an error message and then exits.
2
For more information about DAC, see Using a Dedicated Administrator Connection .
Input/Output Options
-i input_file[,input_file2...]
Identifies the file that contains a batch of SQL statements or stored procedures. Multiple
files may be specified that will be read and processed in order. Do not use any spaces
between file names. sqlcmd will first check to see whether all the specified files exist. If
one or more files do not exist, sqlcmd will exit. The -i and the -Q/-q options are mutually
exclusive.
Path examples:
-i C:\<filename>
-i \\<Server>\<Share$>\<filename>
-o output_file
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 5 of 21
If -u is specified, the output_file is stored in Unicode format. If the file name is not valid,
an error message is generated, and sqlcmd exits. sqlcmd does not support concurrent
writing of multiple sqlcmd processes to the same file. The file output will be corrupted or
incorrect. See the -f switch for more information about file formats. This file will be created
if it does not exist. A file of the same name from a prior sqlcmd session will be
overwritten. The file specified here is not the stdout file. If a stdout file is specified this
file will not be used.
Path examples:
-o C:\< filename>
-o \\<Server>\<Share$>\<filename>
-f < codepage > | i: < codepage > [ < , o: < codepage > ]
Specifies the input and output code pages. The codepage number is a numeric value that
specifies an installed Windows code page. For more information, see Collation Settings in
Setup3.
If no code pages are specified, sqlcmd will use the current code page for both input
and output files, unless the input file is a Unicode file, in which case no conversion is
required.
sqlcmd automatically recognizes both big-endian and little-endian Unicode input
files. If the -u option has been specified, the output will always be little-endian
Unicode.
If no output file is specified, the output code page will be the console code page. This
enables the output to be displayed correctly on the console.
Multiple input files are assumed to be of the same code page. Unicode and non-
Unicode input files can be mixed.
Enter chcp at the command prompt to verify the code page of Cmd.exe.
-u unicode output
Specifies that output_file is stored in Unicode format, regardless of the format of input_file.
-r [ 0 | 1] msgs to stderr
Redirects the error message output to the screen (stderr). If you do not specify a
parameter or if you specify 0, only error messages that have a severity level of 11 or
higher are redirected. If you specify 1, all error message output including PRINT is
redirected. Has no effect if you use -o. By default, messages are sent to stdout.
Sets the SQL Server OLE DB provider to use client regional settings when it converts
currency, and date and time data to character data. The default is server regional settings.
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 6 of 21
Executes a query when sqlcmd starts, but does not exit sqlcmd when the query has
finished running. Multiple-semicolon-delimited queries can be executed. Use quotation
marks around the query, as shown in the following example.
Important:
If -b is specified together with this option, sqlcmd exits on error. -b is described later in
this topic.
Executes a query when sqlcmd starts and then immediately exits sqlcmd. Multiple-
semicolon-delimited queries can be executed.
Use quotation marks around the query, as shown in the following example.
Important:
If -b is specified together with this option, sqlcmd exits on error. -b is described later in
this topic.
-e echo input
Sets the SET QUOTED_IDENTIFIER connection option to ON. By default, it is set to OFF. For
more information, see SET QUOTED_IDENTIFIER (Transact-SQL)4.
-t query time_out
Specifies the number of seconds before a command (or SQL statement) times out. This
option sets the sqlcmd scripting variable SQLCMDSTATTIMEOUT. If a time_out value is not
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 7 of 21
specified, the command does not time out. The query time_out must be a number between
1 and 65535. If the value supplied is not numeric or does not fall into that range, sqlcmd
generates an error message.
Note The actual time out value may vary from the specified time_out value by several
seconds.
-v var=value[ var=value...]
Creates a sqlcmd scripting variable that can be used in a sqlcmd script. Enclose the value
in quotation marks if the value contains spaces. You can specify multiple var="values"
values. If there are errors in any of the values specified, sqlcmd generates an error
message and then exits.
Causes sqlcmd to ignore scripting variables. This is useful when a script contains many
INSERT statements that may contain strings that have the same format as regular
variables, such as $(variable_name).
Formatting Options
-h headers
Specifies the number of rows to print between the column headings. The default is to print
headings one time for each set of query results. This option sets the sqlcmd scripting
variable SQLCMDHEADERS. Use -1 to specify that headers must not be printed. Any value
that is not valid causes sqlcmd to generate an error message and then exit.
-s col_separator
Specifies the column-separator character. The default is a blank space. This option sets the
sqlcmd scripting variable SQLCMDCOLSEP. To use characters that have special meaning to
the operating system such as the ampersand (&), or semicolon (;), enclose the character in
quotation marks ("). The column separator can be any 8-bit character.
-w column_width
Specifies the screen width for output. This option sets the sqlcmd scripting variable
SQLCMDCOLWIDTH. The column width must be a number greater than 8 and less than
65536. If the specified column width does not fall into that range, sqlcmd generates and
error message. The default width is 80 characters. When an output line exceeds the
specified column width, it wraps on to the next line.
This option removes trailing spaces from a column. Use this option together with the -s
option when preparing data that is to be exported to another application. Cannot be used
with the -y or -Y options.
Removes all control characters, such as tabs and new line characters from the output. This
preserves column formatting when data is returned. If 1 is specified, the control characters
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 8 of 21
are replaced by a single space. If 2 is specified, consecutive control characters are replaced
by a single space.
-y display_width
Sets the sqlcmd scripting variable SQLCMDMAXVARTYPEWIDTH. The default = 0 (not set).
It limits the number of characters that are returned for variable length data types:
varchar(max)
nvarchar(max)
varbinary(max)
xml
UDT (user-defined types)
text
ntext
image
Note:
UDTs can be of fixed length depending on the implementation. If this length of a fixed
length UDT is shorter that display_width, the value of the UDT returned is not affected.
However, if the length is longer than display_width, the output is truncated.
If display_width is 0, the output is truncated at 1 MB. You can use the :XML ON command
to prevent truncation of the output. The :XML ON command is described later in this topic.
Important:
Use the -y 0 option with extreme caution because it may cause serious performance
issues on both the server and the network, depending on the size of data returned.
-Y display_width
Specifies that sqlcmd exits and returns a DOS ERRORLEVEL value when an error occurs.
The value that is returned to the DOS ERRORLEVEL variable is 1 when the SQL Server error
message has a severity level greater than 10; otherwise, the value returned is 0. If the -V
option has been set in addition to -b, sqlcmd will not report an error if the severity level is
lower than the values set using -V. Command prompt batch files can test the value of
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 9 of 21
ERRORLEVEL and handle the error appropriately. sqlcmd does not report errors for
severity level 10 (informational messages).
If the sqlcmd script contains an incorrect comment, syntax error, or is missing a scripting
variable, ERRORLEVEL returned is 1.
-V severitylevel
Specifies the lowest severity level that sqlcmd reports. When an error occurs in a Transact
-SQL script, the severity level will be reported only if the severity level is greater than or
equal to the value specified by the -V switch. If the severity level is lower then 0 is
reported. The default error level is 0. Command prompt batch files can test the value of
ERRORLEVEL and handle the error appropriately.
-m error_level
Customizes the display of error messages. The message number, the state, and the error
level are displayed for errors higher than the specified severity level. No information is
displayed for errors at severity levels that are lower than the level specified. Use -1 to
specify that all headers are returned with messages, even informational messages. If -1 is
specified, do not include a space between the parameter and the setting (for example, -m-
1 not -m -1).
This option sets the sqlcmd scripting variable SQLCMDERRORLEVEL, which has a default of
0.
Miscellaneous Options
-a packet_size
Requests a packet of a different size. This option sets the sqlcmd scripting variable
SQLCMDPACKETSIZE. packet_size must be a value between 512 and 32767. The default =
4096. A larger packet size can enhance performance for execution of scripts that have lots
of SQL statements between GO commands. You can request a larger packet size. However,
if the request is denied, sqlcmd uses the server default for packet size.
-c cmd_end
Specifies the batch terminator. By default, commands are terminated and sent to SQL
Server by typing the word "GO" on a line by itself. When you reset the batch terminator, do
not use Transact-SQL reserved keywords or characters that have special meaning to the
operating system, even if they are preceded by a backslash.
Lists the locally configured server computers, and the names of the server computers that
are broadcasting on the network. This parameter cannot be used in combination with other
parameters. The maximum number of server computers that can be listed is 3000. If the
server list is truncated because of the size of the buffer a warning message is displayed.
Note:
Because of the nature of broadcasting on networks, sqlcmd may not receive a timely
response from all servers. Therefore, the list of servers returned may vary for each
invocation of this option.
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 10 of 21
If the optional parameter c is specified, the output appears without the Servers: header line
and each server line is listed without leading spaces. This is referred to as clean output.
Clean output improves the processing performance of scripting languages.
Prints performance statistics for every result set. The following is an example of the format
for performance statistics:
x xact[s]:
Where:
If the optional parameter 1 is specified, the output format of the statistics is in colon-
separated format that can be imported easily into a spreadsheet or processed by a script.
If the optional parameter is any value other than 1, an error is generated and sqlcmd
exits.
Disables commands that might compromise system security when sqlcmd is executed from
a batch file. The disabled commands are still recognized; sqlcmd issues a warning
message and continues. If the optional parameter 1 is specified, sqlcmd generates an
error message and then exits. The following commands are disabled when the -X option is
used:
ED
!! command
Remarks
Options do not have to be used in the order shown in the syntax section.
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 11 of 21
When multiple results are returned, sqlcmd prints a blank line between each result set in a
batch. In addition, the "<x> rows affected" message does not appear when it does not apply to
the statement executed.
To use sqlcmd interactively, type sqlcmd at the command prompt with any one or more of the
6
options described earlier in this topic. For more information, see Using the sqlcmd Utility .
Note:
The total length of the sqlcmd command line in the command environment (Cmd.exe), including
all arguments and expanded variables, is that which is determined by the operating system for
Cmd.exe. This varies by operating system. For Windows Server 2003 and Windows XP, the length
is 8191; and for Windows 2000 and Windows NT4, the length is 2047.
Note:
To view the environmental variables, in Control Panel, open System, and then click the
Advanced tab.
SQLCMDUSER -U R ""
SQLCMDPASSWORD -P -- ""
SQLCMDSERVER -S R "DefaultLocalInstance"
SQLCMDWORKSTATION -H R "ComputerName"
SQLCMDDBNAME -d R ""
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 12 of 21
SQLCMDPACKETSIZE -a R "4096"
SQLCMDERRORLEVEL -m R/W 0
SQLCMDINI R ""
is used.
R indicates the value can only be set one time during program initialization.
R/W indicates that the value can be modified by using the setvar command and subsequent
commands will be influenced by the new value.
sqlcmd Commands
In addition to Transact-SQL statements within sqlcmd, the following commands are also
available:
GO [count] :List
[:] ED :Out
[:] !! :Perftrace
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 13 of 21
:r :Help
:Setvar :Listvar
Important:
To maintain backward compatibility with existing osql scripts, some of the commands
will be recognized without the colon. This is indicated by the [:].
sqlcmd commands are recognized only if they appear at the start of a line.
All sqlcmd commands are case insensitive.
Each command must be on a separate line. A command cannot be followed by a Transact-
SQL statement or another command.
Commands are executed immediately. They are not put in the execution buffer as
statements are.
Editing Commands
[:] ED
Starts the text editor. This editor can be used to edit the current Transact-SQL batch, or
the last executed batch. To edit the last executed batch, the ED command must be typed
immediately after the last batch has completed execution.
The text editor is defined by the SQLCMDEDITOR environment variable. The default editor
is 'Edit'. To change the editor, set the SQLCMDEDITOR environment variable. For example,
to set the editor to Microsoft Notepad, at the command prompt, type:
SET SQLCMDEDITOR=notepad
[:] RESET
:List
Variables
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 14 of 21
Defines sqlcmd scripting variables. Scripting variables have the following format:
$(VARNAME).
Implicitly using a command-line option. For example, the -l option sets the
SQLCMDLOGINTIMEOUT sqlcmd variable.
Explicitly by using the :Setvar command.
By defining an environment variable before you run sqlcmd.
Note:
If a variable defined by using :Setvar and an environment variable have the same name,
the variable defined by using :Setvar takes precedence.
Variable names cannot have the same form as a variable expression, such as $(var).
If the string value of the scripting variable contains blank spaces, enclose the value in
quotation marks. If a value for a scripting variable is not specified, the scripting variable is
dropped.
:Listvar
Note:
Only scripting variables that are set by sqlcmd, and those that are set using
the :Setvar command will be displayed.
Output Commands
Redirect all error output to the file specified by file name, to stderr or to stdout. The Error
command can appear multiple times in a script. By default, error output is sent to stderr.
file name
Creates and opens a file that will receive the output. If the file already exists, it will
be truncated to zero bytes. If the file is not available because of permissions or other
reasons, the output will not be switched and will be sent to the last specified or
default destination.
STDERR
Switches error output to the stderr stream. If this has been redirected, the target to
which the stream has been redirected will receive the error output.
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 15 of 21
STDOUT
Switches error output to the stdout stream. If this has been redirected, the target to
which the stream has been redirected will receive the error output.
Creates and redirects all query results to the file specified by file name, to stderr or to
stdout. By default, output is sent to stdout. If the file already exists, it will be truncated to
zero bytes. The Out command can appear multiple times in a script.
Creates and redirects all performance trace information to the file specified by file name, to
stderr or to stdout. By default performance trace output is sent to stdout. If the file
already exists, it will be truncated to zero bytes. The Perftrace command can appear
multiple times in a script.
Sets the action to be performed when an error occurs during script or batch execution.
When the exit option is used, sqlcmd exits with the appropriate error value.
When the ignore option is used, sqlcmd ignores the error and continues executing the
batch or script. By default, an error message will be printed.
[:] QUIT
Lets you use the result of a SELECT statement as the return value from sqlcmd. The first
column of the first result row is converted to a 4-byte integer (long). MS-DOS passes the
low byte to the parent process or operating system error level. Windows 2000 passes the
whole 4-byte integer. The syntax is:
:EXIT(query)
For example:
:EXIT(SELECT @@ROWCOUNT)
You can also include the EXIT parameter as part of a batch file. For example, at the
command prompt, type:
The sqlcmd utility sends everything between the parentheses ( ) to the server. If a system
stored procedure selects a set and returns a value, only the selection is returned. The EXIT
( ) statement with nothing between the parentheses executes everything before it in the
batch and then exits without a return value.
When an incorrect query is specified, sqlcmd will exit without a return value.
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 16 of 21
:EXIT
Does not execute the batch, and then quits immediately and returns no value.
:EXIT( )
:EXIT(query)
Executes the batch that includes the query, and then quits after it returns the results of the
query.
If RAISERROR is used within a sqlcmd script and a state of 127 is raised, sqlcmd will quit
and return the message ID back to the client. For example:
This error will cause the sqlcmd script to end and return the message ID 50001 to the
client.
The return values -1 to -99 are reserved by SQL Server; sqlcmd defines the following
additional return values:
GO [count]
GO signals both the end of a batch and the execution of any cached Transact-SQL
statements. When specifying a value for count, the cached statements will be executed
count times, as a single batch.
Miscellaneous Commands
:r < filename>
Parses additional Transact-SQL statements and sqlcmd commands from the file specified
by <filename> into the statement cache.
If the file contains statements that arenot followed by GO, you must enter GO on the line
that follows :r.
Note:
<filename> is read relative to the startup directory in which sqlcmd was run.
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 17 of 21
The file will be read and executed after a batch terminator is encountered. You can issue
multiple :r commands. The file may include any sqlcmd command. This includes the batch
terminator GO.
Note:
The line count that is displayed in interactive mode will be increased by one for every :r
command encountered. The :r command will appear in the output of the list command.
:Serverlist
Lists the locally configured servers and the names of the servers broadcasting on the
network.
Time-out options:
0 wait forever
The SQLCMDSERVER scripting variable will reflect the current active connection.
If timeout is not specified, the value of the SQLCMDLOGINTIMEOUT variable is the default.
:connect myserver\instance1
To connect to the default instance of myserver using scripting variables, you would use the
following:
:!! Dir
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 18 of 21
Note:
For more information, see "XML Output Format," later in this topic
:Help
sqlcmd input files can be specified with the -i option or the :r command. Output files can be
specified with the -o option or the :Error, :Out and :Perftrace commands. The following are
some guidelines for working with these files:
:Error, :Out and :Perftrace should use separate <filename>. If the same <filename> is
used, inputs from the commands may be intermixed.
If an input file that is located on a remote server is called from sqlcmd on a local computer
and the file contains a drive file path such as :out c:\OutputFile.txt. The output file will be
created on the local computer and not on the remote server.
Valid file paths include: C:\<filename>, \\<Server>\<Share$>\<filename> and "C:\Some
Folder\<file name>". If there is a space in the path, use quotation marks.
Each new sqlcmd session will overwrite existing files that have the same names.
Informational Messages
sqlcmd prints any informational message that are sent by the server. In the following example,
after the Transact-SQL statements are executed, an informational message is printed.
sqlcmd
USE AdventureWorks;
GO
When you press ENTER, the following informational message is printed: "Changed database
context to 'AdventureWorks'."
sqlcmd first prints a column header that contains the column names specified in the select list.
The column names are separated by using the SQLCMDCOLSEP character. By default, this is a
space. If the column name is shorter than the column width, the output is padded with spaces up
to the next column.
This line will be followed by a separator line that is a series of dash characters. The following
output shows an example.
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 19 of 21
USE AdventureWorks;
FROM Person.Contact;
GO
1 Syed Abbas
2 Catherine Abel
(2 row(s) affected)
Although the ContactID column is only 4 characters wide, it has been expanded to accommodate
the longer column name. By default, output is terminated at 80 characters. This can be changed
by using the -w option, or by setting the SQLCMDCOLWIDTH scripting variable.
XML output that is the result of a FOR XML clause is output, unformatted, in a continuous stream.
When you expect XML output, use the following command: :XML ON.
Note:
sqlcmd returns error messages in the usual format. Notice that the error messages are also
output in the XML text stream in XML format. By using :XML ON, sqlcmd does not display
informational messages.
To set the XML mode off, use the following command: :XML OFF.
The GO command should not appear before the XML OFF command is issued because the XML
OFF command switches sqlcmd back to row-oriented output.
XML (streamed) data and rowset data cannot be mixed. If the XML ON command has not been
issued before a Transact-SQL statement that outputs XML streams is executed, the output will be
garbled. If the XML ON command has been issued, you cannot execute Transact-SQL statements
that output regular row sets.
Note:
The :XML command does not support the SET STATISTICS XML statement.
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 20 of 21
See Also
Other Resources
6
Using the sqlcmd Utility
Using sqlcmd with Scripting Variables5
How to: Connect to the Database Engine Using sqlcmd.exe7
8
Editing SQLCMD Scripts with Query Editor
9
sqlcmd Utility Tutorial
Creating Job Steps10
11
How to: Create a CmdExec Job Step (SQL Server Management Studio)
Links Table
1
http://msdn.microsoft.com/en-us/library/ms161962(v=sql.90).aspx
2
http://msdn.microsoft.com/en-us/library/ms189595(v=sql.90).aspx
3
http://msdn.microsoft.com/en-us/library/ms143508(v=sql.90).aspx
4
http://msdn.microsoft.com/en-us/library/ms174393(v=sql.90).aspx
5
http://msdn.microsoft.com/en-us/library/ms188714(v=sql.90).aspx
6
http://msdn.microsoft.com/en-us/library/ms180944(v=sql.90).aspx
7
http://msdn.microsoft.com/en-us/library/ms188247(v=sql.90).aspx
8
http://msdn.microsoft.com/en-us/library/ms174187(v=sql.90).aspx
9
http://msdn.microsoft.com/en-us/library/ms170207(v=sql.90).aspx
10
http://msdn.microsoft.com/en-us/library/ms187056(v=sql.90).aspx
11
http://msdn.microsoft.com/en-us/library/ms190264(v=sql.90).aspx
12
http://msdn.microsoft.com/en-us/library/ms166016(v=sql.90).aspx
Community Content
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012
sqlcmd Utility Page 21 of 21
The default values given for the -y and -Y command-line options are transposed in the Command
-line Options section. They are specified correctly for their corresponding scripting variables in the
Scripting Variables section.
The -y description incorrectly says "The default = 0 (not set)." The default is actually 256.
The -Y description incorrectly says "The default is 256." The default is actually 0.
1/18/2012
JosephJames
The document above states that "If the -P option is used at the end of the command prompt
without a password sqlcmd uses the default password (NULL)". However it doesn't work.
>sqlcmd -U sa -P
Sqlcmd: '-P': Missing argument. Enter '-?' for help.
9/3/2009
David Furtney
http://msdn.microsoft.com/en-us/library/ms162773(d=printer,v=sql.90).aspx 4/17/2012