APPENDIX D

image

SQLCMD Quick Reference

SQLCMD is the standard text-based tool for executing batches of T-SQL on SQL Server. As a text-based tool, SQLCMD provides a lightweight but powerful tool for automating T-SQL batches. This appendix is designed as a quick reference to SQLCMD. The descriptions of many of the features and the functionality given here differ from BOL in some instances; the descriptions provided in this appendix are based on extensive testing of SQLCMD.

Command-Line Options

SQLCMD provides several command-line options to provide flexibility in connecting to SQL Server and executing T-SQL batches in a database. The full format for SQLCMD is shown here:

sqlcmd [ [-U login_id ] [-P password ] | [-E] ] [-C]
[-S server [instance] ] [-d db_name] [-H workstation]
[-l login timeout] [-t query timeout] [-h headers] [-s column_separator] [-w column_width]
[-a packet_size] [-I] [-L[c] ] [-W] [-r[o|1]] [-q "query"] [-Q "query" and exit]
[-c batch_term] [-e] [-m error Level] [-V Severity Level] [-b] [-N]  [-K]
[-i input_file [,input_file2 [, ...] ] ] [-o output_file] [-u]
[-v var = "value" [,var2 = "value2"] [,...] ] [-X[1 ] [-x] [-?]
[-z new_password] [-Z new_password] [-f codepage | i:in_codepage [,o:out_codepage] ]
[-k[l|2] ] [-y display_width] [-Y display_width]
[-p[1 ] [-R] [-A]

The available command-line options are listed in Table D-1. The SQLCMD command-line options are case sensitive, so, for example, -v is a different option from -V.

Table D-1. SQLCMD Command-Line Options

Option

Description

-?

Displays the SQLCMD help/syntax screen.

-A

Tells SQLCMD to log in to SQL Server with a dedicated administrator connection. This type of connection is usually used for troubleshooting.

-a packet_size

Requests communications with a specific packet size. The default is 4096. packet_size must be in the range 512 to 32767.

-b

Specifies that SQLCMD exits on an error and returns an ERRORLEVEL value to the operating system. When this option is set, a SQL error of severity 11 or greater returns an ERRORLEVEL of 1; an error or message of severity 10 or less returns an ERRORLEVEL of 0. If the -V option is also used, SQLCMD reports only the errors with a severity greater than or equal to the severity_level (level 11 or greater) specified with the -V option.

-c batch_term

Specifies the batch terminator. By default, it’s the GO keyword. Avoid using special characters and reserved words as the batch terminator.

-C

Specifies that the server certificate can be trusted implicitly without validation used by the client.

-d db_name

Specifies the database to use after SQLCMD connects to SQL Server. Alternatively, you can set this option via the SQLCMDDBNAME environment variable. If the database specified doesn’t exist, SQLCMD exits with an error.

-E

Uses a trusted connection (Windows authentication mode) to connect to SQL Server. This option ignores the SQLCMDUSER and SQLCMDPASSWORD environment variables, and you can’t use it with the -U and -P options.

-e

Prints (echoes) input scripts to the standard output device (usually the screen by default).

-f codepage | i:in_codepage [,oout_codepage]

Specifies the code pages for input and output. If i: is specified, in_codepage is the input code page. If o: is specified, out_codepage is the output code page. If i: and o: aren’t specified, the codepage supplied is the code page for both input and output. To specify a code page, use its numeric identifier. The following code pages are supported by SQL Server 2005:

Code Page Number

Code Page Name

437

MS-DOS US English

850

Multilingual (MS-DOS Latin1)

874

Thai

932

Japanese

936

Chinese (Simplified)

949

Korean

950

Chinese(Traditional)

1250

Central European

1251

Cyrillic

1252

Latin1 (ANSI)

1253

Greek

1254

Turkish

1255

Hebrew

1256

Arabic

1257

Baltic

1258

Vietnamese

-H workstation

The -H option sets the workstation name. You can use -H to differentiate between sessions with commands such as sp_who.

-h headers

Specifies the number of rows of data to print before a new column header is generated. The value must be from -1 (no headers) to 2147483647. The default value of 0 prints headings once for each set of results.

-I

Sets the connection QUOTED_IDENTIFIER option to ON. Turning on the QUOTED_IDENTIFIER option makes SQL Server follow the ANSI SQL-92 rules for quoted identifiers. This option is set to OFF by default.

-i input_file [,input_file2] [,...]

Specifies that SQLCMD should use files that contain batches of T-SQL statements for input. The files are processed in order from left to right. If any of the files don’t exist, SQLCMD exits with an error. You can use the GO batch terminator in your SQL script files.

-k [1|2]

-k removes control characters from the output. If 1 is specified, control characters are replaced one for one with spaces. If 2 is specified, consecutive control characters are replaced with a single space.

-K

Specifies the intent of the application workload that is connecting to the server that is a secondary replica in the AlwaysOn availability group. The only value that can be specified currently is ReadOnly.

-L [c]

-L returns a listing of available SQL Server machines on the network and local computer. If the -Lc format is used, a “clean” listing is returned without heading information. The listing is limited to a maximum of 3,000 servers. Note that because of the way SQL Server broadcasts to gather server information, any servers that don’t respond in a timely manner aren’t included in the list. You can’t use the -L option with other options.

-l timeout

Specifies the login timeout. The timeout value must be from 0 to 65534. The default value is 8 seconds, and a value of 0 is no timeout (infinite).

-m error_level

Defines an error-message customization level. Only errors with a severity greater than the specified level are displayed. If error_level is -1, all messages are returned, even informational messages.

-N

Specifies that the client connection is encrypted.

-o output_file

Specifies the file to which SQLCMD should direct output. If -o isn’t specified, SQLCMD defaults to standard output (usually the screen).

-P password

Specifies a password to log in to SQL Server when using SQL authentication mode. If -P is omitted, SQLCMD looks for the SQLCMDPASSWORD environment variable to get the password to log in. If the SQLCMDPASSWORD environment variable isn’t found, SQLCMD prompts you for the password to log in using SQL authentication mode. If neither -P nor -U is specified and the corresponding environment variables aren’t set, SQLCMD attempts to log in using Windows authentication mode.

-p [1]

-p prints performance statistics for each result set. Specifying 1 produces colon-separated output.

-Q "query" and -q "query"

Both execute a SQL query/command from the command line. -q remains in SQLCMD after query completion. -Q exits SQLCMD after completion.

-R

Specifies client regional settings for currency and date/time formatting.

-r [0|1]

-r redirects error-message output to the standard error-output device—the monitor by default. If 1 is specified, all error messages and informational messages are redirected. If 0 or no number is specified, only error messages with a severity of 11 or greater are redirected. The redirection doesn’t work with the -o option; it does work if standard output is redirected with the Windows command-line redirector (>).

-S server [instance]

Specifies  the SQL Server server or named instance to which SQLCMD should connect. If this option isn’t specified, SQLCMD connects to the default SQL Server instance on the local machine.

-s column_separator

Sets the column-separator character. By default, the column separator is a space character. Column_separator can be enclosed in quotes, which is useful if you want to use a character that the operating system recognizes as a special character, such as the greater-than sign (>).

-t timeout

Specifies the SQL query/command timeout in seconds. The timeout value must be in the range 0 to 65535. If -t isn’t specified, or if it’s set to 0, queries/commands don’t time out.

-U login_id

Specifies the user login ID to log in to SQL Server using SQL authentication mode. If the -U option is omitted, SQLCMD looks for the SQLCMDUSER environment variable to get the login password. If the -U option is omitted, SQLCMD attempts to use the current user’s Windows login name to log in.

-u

Specifies that the output of SQLCMD is in Unicode format. Use this option with the -o option.

-V severity_level

Specifies the lowest severity level that SQLCMD reports back. Errors and messages of a severity less than severity_level are reported as 0. Severity_level must be in the range 1 to 25. In a command-line batch file, -V returns the severity level of any SQL Server errors encountered via the ERRORLEVEL so that your batch file can take appropriate action.

-v var = "value"

[,var2 = "value2"]

[,...]

Sets scripting variables that SQLCMD can use in your scripts to the specified values. Scripting variables are described later in this appendix.

-W

Removes trailing spaces from a column. You can use this option with the -s option when preparing data that is to be exported to another application. You can’t use -W in conjunction with the -Y or -y option.

-w column_width

Specifies the screen width for output. The width value must be in the range 9 to 65535. The default of 0 is equivalent to the width of the output device. For screen output, the default is the width of the screen. For files, the default width is unlimited.

-X [1]

-X disables options that can compromise security in batch files. Specifically, -X does the following:

  • Disables the SQLCMD:!! and :ED commands
  • Prevents SQLCMD from using operating system environment variables
  • Disables the SQLCMD startup script

If a disabled command is encountered, SQLCMD issues a warning and continues processing. If the optional 1 is specified with -X, SQLCMD exits with an error when a disabled command is encountered. Descriptions of SQLCMD commands, script variables, environment variables, and the startup script are detailed later in this appendix.

-x

Forces SQLCMD to ignore scripting variables.

-Y display_width

Limits the number of characters returned for the char, nchar, varchar (8,000 bytes or less), nvarchar (4,000 bytes or less), and sql_variant data types.

-y display_width

Limits the number of characters returned for variable-length data types such as varchar(max), varbinary(max), xml, text, and fixed-length or variable-length user-defined types (UDTs).

-Z new_password and -z new_password

When used with SQL authentication (the -U and -P options), -Z and -z change the SQL login password. If the -P option isn’t specified, SQLCMD prompts you for the current password. -z changes the password and enters interactive mode. -Z exits SQLCMD immediately after the password is changed.

Scripting Variables

SQLCMD supports scripting variables, which allow you to dynamically replace script content at execution time. This lets you use a single script in multiple scenarios. By using scripting variables, for instance, you can execute a single script against different servers or databases without modification. SQLCMD allows you to set your own custom scripting variables with the -v command-line option. If more than one scripting variable is specified with the same name, the variable with the highest precedence (according to the following list) is used:

  1. System-level environment variables have the highest precedence.
  2. User-level environment variables are next.
  3. Variables set via the command shell SET option are next.
  4. Variables set via the SQLCMD -v command-line option are next.
  5. Variables set inside a SQLCMD batch via the :SETVAR command have the lowest precedence.

Image Note  The -X and -x options disable startup-script execution and environment-variable access, respectively. -x also prevents SQLCMD from dynamically replacing scripting-variable references in your code with the appropriate values. This is a feature designed for secure environments where scripting-variable usage could compromise security.

SQLCMD also provides several predefined scripting variables, which are listed in Table D-2. You can set the predefined read-only SQLCMD scripting variables via the command shell SET option or through SQLCMD command-line options; you can’t alter them from within a SQLCMD script with :SETVAR.

Table D-2. SQLCMD Scripting Variables

TableD-2.jpg

Commands

SQLCMD recognizes a set of commands that aren’t part of T-SQL. These SQLCMD commands aren’t recognized by other query tools; they’re not even recognized by SSMS (except when you run it in SQLCMD mode). SQLCMD commands all begin on a line with a colon (:) to identify them as different from T-SQL statements. You can intersperse SQLCMD commands within your T-SQL scripts. Table D-3 lists the SQLCMD commands available.

Image Tip  For backward compatibility with older osql scripts, you can enter the following commands without a colon prefix: !!, ED, RESET, EXIT, and QUIT. Also, SQLCMD commands are case insensitive, they must appear at the beginning of a line, and they must be on their own line. A SQLCMD command can’t be followed on the same line by a T-SQL statement or another SQLCMD command.

Table D-3. SQLCMD Commands

Command

Description

:!!

Invokes the command shell. This command executes the specified operating system command in the command shell.

:CONNECT server [instance]

Connects to a SQL Server instance.

[-ltimeout] [-Uuser [-Ppassword] ]

The server name (server) and instance name (instance) are specified in the command. When :CONNECT is executed, the current connection is closed. You can use the following options with the :CONNECT command: -l specifies the login timeout (specified in seconds; 0 equals no timeout); -U specifies the SQL authentication username; and -P specifies the SQL authentication password.

:ED

Starts the text editor to edit the current batch or the last executed batch. The SQLCMDEDITOR environment variable defines the application used as the SQLCMD editor. The default is the Windows EDIT utility.

:ERROR destination

Redirects error messages to the specified destination. destination can be a file name, STDOUT for standard output, or STDERR for standard error output.

:EXIT [()|(query)]

Has three forms: :EXIT alone immediately exits without executing the batch and with no return code. :EXIT() executes the current batch and exits with no return code. :EXIT(query) executes the batch, including the query specified, and returns the first value of the first result row of the query as a 4-byte integer to the operating system.

GO [n]

The batch terminator. It executes the statements in the cache. If n is specified, GO executes the statement n times.

:HELP

Displays a list of SQLCMD commands.

:LIST

Lists the contents of the current batch of statements in the statement cache.

:LISTVAR

Lists all the SQLCMD scripting variables (that have been set) and their current values.

:ON ERROR action

Specifies the action SQLCMD should take when an error is encountered. action can be one of two values: EXIT stops processing and exits, returning the appropriate error code. IGNORE disregards the error and continues processing.

:OUT destination

Redirects output to the specified destination. destination can be a file name, STDOUT for standard output, or STDERR for standard error output. Output is sent to STDOUT by default.

:PERFTRACE destination

Redirects performance trace/timing information to the specified destination. destination can be a file name, STDOUT for standard output, or STDERR for standard error output. Trace information is sent to STDOUT by default.

:QUIT

Quits SQLCMD immediately.

:R filename

Reads in the contents of the specified file and appends it to the statement cache.

:RESET

Resets/clears the statement cache.

:SERVERLIST

Lists all SQL Server instances on the local machine and any servers broadcasting on the local network. If SQLCMD doesn’t receive timely responses from a server on the network, it may not be listed.

:SETVAR var [value]

Allows you to set or remove SQLCMD scripting variables. To remove a SQLCMD scripting variable, use the :SETVAR var format. To set a SQLCMD scripting variable to a value, use the :SETVAR var value format.

:XML ON|OFF

Indicates to SQLCMD that you expect XML output from SQL Server (that is, the SELECT statement’s FOR XML clause). Use :XML ON before your SQL batch is run and :XML OFF after the batch has executed (after the GO batch terminator).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset