Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Califique este contenido
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
sqlcmd Utility

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 ODBC to execute Transact-SQL batches.

Important noteImportant

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 ODBC driver. 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.

Currently, sqlcmd does not require a space between the command line option and the value. However, in a future release, a space may be required between the command line option and the value.

sqlcmd 
   -a packet_size
   -A (dedicated administrator connection)
   -b (terminate batch job if there is an error)
   -c batch_terminator
   -C (trust the server certificate)
   -d db_name
   -e (echo input)
   -E (use trusted connection)
   -f codepage | i:codepage[,o:codepage] | o:codepage[,i:codepage]
   -h rows_per_header
   -H workstation_name
   -i input_file
   -I (enable quoted identifiers)
   -k[1 | 2] (remove or replace control characters)
   -K application_intent
   -l login_timeout
   -L[c] (list servers, optional clean output)
   -m error_level
   -N (encrypt connection)
   -o output_file
   -p[1] (print statistics, optional colon format)
   -P password
   -q "cmdline query"
   -Q "cmdline query" (and exit)
   -r[0 | 1] (msgs to stderr)
   -R (use client regional settings)
   -s col_separator
   -S [protocol:]server[\instance_name][,port]
   -t query_timeout
   -u (unicode output file)
   -U login_id
   -v var = "value"
   -V error_severity_level
   -w column_width
   -W (remove trailing spaces)
   -x (disable variable substitution)
   -X[1] (disable commands, startup script, environment variables and optional exit)
   -y variable_length_type_display_width
   -Y fixed_length_type_display_width
   -z new_password 
   -Z new_password (and exit)

   -? (usage)
Login-Related Options

-A

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. For more information about DAC, see Diagnostic Connection for Database Administrators.

-C

This switch is used by the client to configure it to implicitly trust the server certificate without validation. This option is equivalent to the ADO.NET option TRUSTSERVERCERTIFICATE = true.

-ddb_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.

-llogin_timeout

Specifies the number of seconds before a sqlcmd login to the ODBC driver 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.

-E

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.

-Hworkstation_name

A workstation name. This option sets the sqlcmd scripting variable SQLCMDWORKSTATION. The workstation name is listed in the hostname column of the sys.processes catalog view and can be returned using the stored procedure sp_who. If this option is not specified, the default is the current computer name. This name can be used to identify different sqlcmd sessions.

-Kapplication_intent

Declares the application workload type when connecting to a server. The only currently supported value is ReadOnly. If -K is not specified, the sqlcmd utility will not support connectivity to a secondary replica in an AlwaysOn availability group. For more information, see Readable Secondary Replicas (AlwaysOn Availability Groups).

-N

This switch is used by the client to request an encrypted connection.

-Ppassword

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 noteSecurity Note

Do not use a blank password. Use a strong password. For more information, see Strong Passwords.

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:

SET SQLCMDPASSWORD= p@a$$w0rd

Security noteSecurity Note

The password will be visible to anyone who can see your computer monitor.

At the following command prompt, type:

sqlcmd

If the user name and password combination is incorrect, an error message is generated.

NoteNote

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 used with the -E option, an error message is generated.

If the -P option is followed by more than one argument, an error message is generated and the program exits.

-S [protocol:]server[\instance_name][,port]

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.

protocol can be tcp (TCP/IP), lpc (shared memory), or np (named pipes).

If you do not specify a server_name [ \instance_name ] when you start sqlcmd, SQL Server checks for and uses the SQLCMDSERVER environment variable.

NoteNote

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.

-Ulogin_id

Is the user login ID.

NoteNote

The OSQLUSER environment variable is available for backward compatibility. The SQLCMDUSER environment variable takes precedence over the OSQLUSER environment variable. This means that sqlcmd and osql can be used next to each other without interference. It also means that existing osql scripts will continue to work.

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.

-znew_password

Change password:

sqlcmd -U someuser -P s0mep@ssword -z a_new_p@a$$w0rd

-Znew_password

Change password and exit:

sqlcmd -U someuser -P s0mep@ssword -Z a_new_p@a$$w0rd

Input/Output Options

-fcodepage | i:codepage[,o:codepage] | o:codepage[,i:codepage]

Specifies the input and output code pages. The codepage number is a numeric value that specifies an installed Windows code page.

Code-page conversion rules:

  • 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.

-iinput_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>

-i "C:\Some Folder\<file name>"

File paths that contain spaces must be enclosed in quotation marks.

This option may be used more than once: -i input_file -I I input_file.

-ooutput_file

Identifies the file that receives output from sqlcmd.

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>

-o "C:\Some Folder\<file name>"

File paths that contain spaces must be enclosed in quotation marks.

-r[0 | 1]

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.

-R

Causes sqlcmd to localize numeric, currency, date, and time columns retrieved from SQL Server based on the client’s locale. By default, these columns are displayed using the server’s regional settings.

-u

Specifies that output_file is stored in Unicode format, regardless of the format of input_file.

Query Execution Options

-e

Writes input scripts to the standard output device (stdout).

-I

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).

-q"cmdline query"

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.

At the command prompt, type:

sqlcmd -d AdventureWorks2012 -q "SELECT FirstName, LastName FROM Person.Person WHERE LastName LIKE 'Whi%';"

sqlcmd -d AdventureWorks2012 -q "SELECT TOP 5 FirstName FROM Person.Person;SELECT TOP 5 LastName FROM Person.Person;"

Important noteImportant

Do not use the GO terminator in the query.

If -b is specified together with this option, sqlcmd exits on error. -b is described later in this topic.

-Q"cmdline query"

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.

At the command prompt, type:

sqlcmd -d AdventureWorks2012 -Q "SELECT FirstName, LastName FROM Person.Person WHERE LastName LIKE 'Whi%';"

sqlcmd -d AdventureWorks2012 -Q "SELECT TOP 5 FirstName FROM Person.Person;SELECT TOP 5 LastName FROM Person.Person;"

Important noteImportant

Do not use the GO terminator in the query.

If -b is specified together with this option, sqlcmd exits on error. -b is described later in this topic.

-tquery_timeout

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 specified, the command does not time out. The query time_out must be a number between 1 and 65534. If the value supplied is not numeric or does not fall into that range, sqlcmd generates an error message.

NoteNote

The actual time out value may vary from the specified time_out value by several seconds.

-vvar = value[ var = value...]

Creates a sqlcmdscripting 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.

sqlcmd -v MyVar1=something MyVar2="some thing"

sqlcmd -v MyVar1=something -v MyVar2="some thing"

-x

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

-hheaders

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.

-k [1 | 2]

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 are replaced by a single space. If 2 is specified, consecutive control characters are replaced by a single space. -k is the same as -k1.

-scol_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.

-wcolumn_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.

-W

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.

-yvariable_length_type_display_width

Sets the sqlcmd scripting variable SQLCMDMAXFIXEDTYPEWIDTH. The default is 256. It limits the number of characters that are returned for the large variable length data types:

  • varchar(max)

  • nvarchar(max)

  • varbinary(max)

  • xml

  • UDT (user-defined data types)

  • text

  • ntext

  • image

NoteNote

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.

Important noteImportant

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.

-Yfixed_length_type_display_width

Sets the sqlcmd scripting variable SQLCMDMAXVARTYPEWIDTH. The default is 0 (unlimited). Limits the number of characters that are returned for the following data types:

  • char(n), where 1<=n<=8000

  • nchar(nn), where 1<=n<=4000

  • varchar(nn), where 1<=n<=8000

  • nvarchar(nn), where 1<=n<=4000

  • varbinary(nn), where 1<=n<=4000

  • variant

Error Reporting Options

-b

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 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.

-merror_level

Controls which error messages are sent to stdout. Messages that have a severity level less than or equal to this level are sent. When this value is set to -1, all messages including informational messages, are sent. Spaces are not allowed between the -m and -1. For example, -m-1 is valid, and -m -1 is not.

This option also sets the sqlcmd scripting variable SQLCMDERRORLEVEL. This variable has a default of 0.

-Verror_severity_level

Controls the severity level that is used to set the ERRORLEVEL variable. Error messages that have severity levels less than or equal to this value set ERRORLEVEL. Values that are less than 0 are reported as 0. Batch and CMD files can be used to test the value of the ERRORLEVEL variable.

Miscellaneous Options

-apacket_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.

-cbatch_terminator

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.

-L[c]

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.

NoteNote

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.

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.

-p[1]

Prints performance statistics for every result set. The following is an example of the format for performance statistics:

Network packet size (bytes): n

x xact[s]:

Clock Time (ms.): total t1 avg t2 (t3 xacts per sec.)

Where:

x = Number of transactions that are processed by SQL Server.

t1 = Total time for all transactions.

t2 = Average time for a single transaction.

t3 = Average number of transactions per second.

All times are in milliseconds.

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.

-X[1]

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

If the -X option is specified, it prevents environment variables from being passed on to sqlcmd. It also prevents the startup script specified by using the SQLCMDINI scripting variable from being executed. For more information about sqlcmd scripting variables, see Use sqlcmd with Scripting Variables.

-?

Displays the syntax summary of sqlcmd options.

Options do not have to be used in the order shown in the syntax section.

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 options described earlier in this topic. For more information, see Use the sqlcmd Utility

NoteNote

The options -L, -Q, -Z or -i cause sqlcmd to exit after execution.

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.

  1. System-level environmental variables.

  2. User-level environmental variables

  3. Command shell (SET X=Y) set at command prompt before running sqlcmd.

  4. sqlcmd -v X=Y

  5. :Setvar X Y

NoteNote

To view the environmental variables, in Control Panel, open System, and then click the Advanced tab.

Variable

Related switch

R/W

Default

SQLCMDUSER

-U

R

""

SQLCMDPASSWORD

-P

--

""

SQLCMDSERVER

-S

R

"DefaultLocalInstance"

SQLCMDWORKSTATION

-H

R

"ComputerName"

SQLCMDDBNAME

-d

R

""

SQLCMDLOGINTIMEOUT

-l

R/W

"8" (seconds)

SQLCMDSTATTIMEOUT

-t

R/W

"0" = wait indefinitely

SQLCMDHEADERS

-h

R/W

"0"

SQLCMDCOLSEP

-s

R/W

" "

SQLCMDCOLWIDTH

-w

R/W

"0"

SQLCMDPACKETSIZE

-a

R

"4096"

SQLCMDERRORLEVEL

-m

R/W

0

SQLCMDMAXVARTYPEWIDTH

-y

R/W

"256"

SQLCMDMAXFIXEDTYPEWIDTH

-Y

R/W

"0" = unlimited

SQLCMDEDITOR

R/W

"edit.com"

SQLCMDINI

R

""

SQLCMDUSER, SQLCMDPASSWORD and SQLCMDSERVER are set when :Connect

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.

In addition to Transact-SQL statements within sqlcmd, the following commands are also available:

GO [count]

:List

[:] RESET

:Error

[:] ED

:Out

[:] !!

:Perftrace

[:] QUIT

:Connect

[:] EXIT

:On Error

:r

:Help

:ServerList

:XML [ON | OFF]

:Setvar

:Listvar

Be aware of the following when you use sqlcmd commands:

  • All sqlcmd commands, except GO, must be prefixed by a colon (:).

    Important noteImportant

    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 Transact-SQL 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

Clears the statement cache.

:List

Prints the content of the statement cache.

Variables

:Setvar <var> [ "value" ]

Defines sqlcmd scripting variables. Scripting variables have the following format: $(VARNAME).

Variable names are case insensitive.

Scripting variables can be set in the following ways:

  • 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.

NoteNote

The -X option prevents environment variables from being passed on to sqlcmd.

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 must not contain blank space characters.

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

Displays a list of the scripting variables that are currently set.

NoteNote

Only scripting variables that are set by sqlcmd, and those that are set using the :Setvar command will be displayed.

Output Commands

:Error <filename>|STDERR|STDOUT

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.

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.

:Out <filename>| STDERR| STDOUT

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.

:Perftrace <filename>| STDERR| STDOUT

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.

Execution Control Commands

:On Error[ exit | ignore]

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

Causes sqlcmd to exit.

[:] EXIT[ (statement) ]

Lets you use the result of a SELECT statement as the return value from sqlcmd. If numeric, the first column of the last 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 200x 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:

sqlcmd -Q "EXIT(SELECT COUNT(*) FROM '%1')"

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.

Here is a list of EXIT formats:

  • :EXIT

Does not execute the batch, and then quits immediately and returns no value.

  • :EXIT( )

Executes the batch, and then quits and returns no value.

  • :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:

RAISERROR(50001, 10, 127)

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:

Return Values

Description

-100

Error encountered prior to selecting return value.

-101

No rows found when selecting return value.

-102

Conversion error occurred when selecting return value.

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 Transact-SQL statements that are not followed by GO, you must enter GO on the line that follows :r.

NoteNote

<filename> is read relative to the startup directory in which sqlcmd was run.

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.

NoteNote

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.

:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]]

Connects to an instance of SQL Server. Also closes the current connection.

Time-out options:

0

wait forever

n>0

wait for n seconds

The SQLCMDSERVER scripting variable will reflect the current active connection.

If timeout is not specified, the value of the SQLCMDLOGINTIMEOUT variable is the default.

If only user_name is specified (either as an option, or as an environment variable), the user will be prompted to enter a password. This is not true if the SQLCMDUSER or SQLCMDPASSWORD environment variables have been set. If neither options nor environment variables are provided, Windows Authentication mode is used to login. For example to connect to an instance, instance1, of SQL Server, myserver, by using integrated security you would use the following:

:connect myserver\instance1

To connect to the default instance of myserver using scripting variables, you would use the following:

:setvar myusername test

:setvar myservername myserver

:connect $(myservername) $(myusername)

[:] !!< command>

Executes operating system commands. To execute an operating system command, start a line with two exclamation marks (!!) followed by the operating system command. For example:

:!! Dir

NoteNote

The command is executed on the computer on which sqlcmd is running.

:XML [ON | OFF]

For more information, see "XML Output Format," later in this topic

:Help

Lists sqlcmd commands together with a short description of each command.

sqlcmd File Names

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.

At the command prompt, type the following:

sqlcmd

At the sqlcmd prompt type:

USE AdventureWorks2012;

GO

When you press ENTER, the following informational message is printed: "Changed database context to 'AdventureWorks2012'."

Output Format from Transact-SQL Queries

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.

Start sqlcmd. At the sqlcmd command prompt, type the following:

USE AdventureWorks2012;

SELECT TOP (2) BusinessEntityID, FirstName, LastName

FROM Person.Person;

GO

When you press ENTER, the following result set is retuned.

BusinessEntityID FirstName    LastName

---------------- ------------ ----------

285              Syed         Abbas

293              Catherine    Abel

(2 row(s) affected)

Although the BusinessEntityID 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 Format

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.

NoteNote

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.

NoteNote

The :XML command does not support the SET STATISTICS XML statement.

Use the following practices to help maximize security and efficiency.

  • Use integrated security.

  • Use -X in automated environments.

  • Secure input and output files by using appropriate NTFS file system permissions.

  • To increase performance, do as much in one sqlcmd session as you can, instead of in a series of sessions.

  • Set time-out values for batch or query execution higher than you expect it will take to execute the batch or query.

sqlcmd (utilidad)

La utilidad sqlcmd permite escribir instrucciones Transact-SQL , procedimientos del sistema y archivos de script en el símbolo del sistema, en el Editor de consultas en modo SQLCMD, en un archivo de script de Windows o en un paso de trabajo del sistema operativo (Cmd.exe) de un trabajo del Agente de SQL Server. Esta utilidad usa ODBC para ejecutar lotes de Transact-SQL.

Nota importanteImportante

SQL Server Management Studio usa Microsoft .NET Framework SqlClient para la ejecución en modo normal y SQLCMD en el Editor de consultas. Cuando sqlcmd se ejecuta desde la línea de comandos, sqlcmd usa el controlador ODBC. Dado que se pueden aplicar diferentes opciones predeterminadas, podría obtener un comportamiento diferente al ejecutar la misma consulta en el modo SQLCMD de SQL Server Management Studio y en la utilidad sqlcmd.

Actualmente, sqlcmd no requiere un espacio entre la opción de línea de comandos y el valor. Sin embargo, en versiones futuras, se puede requerir un espacio entre la opción de línea de comandos y el valor.

sqlcmd 
   -a packet_size
   -A (dedicated administrator connection)
   -b (terminate batch job if there is an error)
   -c batch_terminator
   -C (trust the server certificate)
   -d db_name
   -e (echo input)
   -E (use trusted connection)
   -f codepage | i:codepage[,o:codepage] | o:codepage[,i:codepage]
   -h rows_per_header
   -H workstation_name
   -i input_file
   -I (enable quoted identifiers)
   -k[1 | 2] (remove or replace control characters)
   -K application_intent
   -l login_timeout
   -L[c] (list servers, optional clean output)
   -m error_level
   -N (encrypt connection)
   -o output_file
   -p[1] (print statistics, optional colon format)
   -P password
   -q "cmdline query"
   -Q "cmdline query" (and exit)
   -r[0 | 1] (msgs to stderr)
   -R (use client regional settings)
   -s col_separator
   -S [protocol:]server[\instance_name][,port]
   -t query_timeout
   -u (unicode output file)
   -U login_id
   -v var = "value"
   -V error_severity_level
   -w column_width
   -W (remove trailing spaces)
   -x (disable variable substitution)
   -X[1] (disable commands, startup script, environment variables and optional exit)
   -y variable_length_type_display_width
   -Y fixed_length_type_display_width
   -z new_password 
   -Z new_password (and exit)

   -? (usage)
Opciones relacionadas con el inicio de sesión

-A

Inicia sesión en SQL Server con una Conexión de administrador dedicada (DAC). Este tipo de conexión se utiliza para solucionar problemas de un servidor. Solo funcionará con equipos servidores que admitan DAC. Si DAC no está disponible, sqlcmd genera un mensaje de error y, después, se cierra. Para obtener más información acerca de DAC, vea Conexión de diagnóstico para administradores de bases de datos.

-C

Este modificador lo usa el cliente para configurarlo de forma que confíe implícitamente en el certificado de servidor sin validación. Esta opción es equivalente a la opción de ADO.NET TRUSTSERVERCERTIFICATE = true.

-ddb_name

Emite una instrucción USE db_name cuando se inicia sqlcmd. Esta opción establece la variable de scripting de sqlcmd SQLCMDDBNAME. Especifica la base de datos inicial. El valor predeterminado es la propiedad de base de datos predeterminada del inicio de sesión. Si la base de datos no existe, se genera un mensaje de error y sqlcmd se cierra.

-llogin_timeout

Especifica el número de segundos que tienen que transcurrir antes de que un inicio de sesión de sqlcmd en el proveedor ODBC agote el tiempo de espera cuando se intente conectar a un servidor. Esta opción establece la variable de scripting de sqlcmd SQLCMDLOGINTIMEOUT. El tiempo de espera predeterminado para el inicio de sesión de sqlcmd es de ocho segundos. El período de tiempo de espera de inicio de sesión debe ser un número comprendido entre 0 y 65534. Si el valor proporcionado no es numérico o no está dentro de este intervalo, sqlcmd genera un mensaje de error. El valor 0 especifica que el tiempo de espera es infinito.

-E

Usa una conexión de confianza en lugar de usar un nombre de usuario y una contraseña para iniciar sesión en SQL Server. De manera predeterminada, si no se especifica -E, sqlcmd usa la opción de conexión de confianza.

La opción -E omite la posible configuración de la variable de entorno de nombre de usuario y contraseña, como SQLCMDPASSWORD. Si se usa la opción -E junto con la opción -U o -P, se genera un mensaje de error.

-Hworkstation_name

Un nombre de estación de trabajo. Esta opción establece la variable de scripting de sqlcmd SQLCMDWORKSTATION. El nombre de la estación de trabajo se muestra en la columna hostname de la vista de catálogo sys.processes y se puede devolver mediante el procedimiento almacenado sp_who. Si no se especifica esta opción, el nombre actual del equipo es el valor predeterminado. Este nombre se puede usar para identificar diferentes sesiones de sqlcmd.

-Kapplication_intent

Declara el tipo de carga de trabajo de la aplicación al conectarse a un servidor. El único valor actualmente admitido es de solo lectura. Si no se especifica -K, la utilidad sqlcmd no admitirá la conectividad con una réplica secundaria en el grupo de disponibilidad AlwaysOn. Para obtener más información, vea Réplicas secundarias legibles (grupos de disponibilidad de AlwaysOn).

-N

Este modificador lo usa el cliente para solicitar una conexión cifrada.

-Ppassword

Es una contraseña especificada por el usuario. En las contraseñas se distingue entre mayúsculas y minúsculas. Si se usa la opción -U y no la opción -P, y además no se ha establecido la variable de entorno SQLCMDPASSWORD, sqlcmd solicita al usuario una contraseña. Si se usa la opción -P al final del símbolo del sistema sin especificar ninguna contraseña, sqlcmd usa la contraseña predeterminada (NULL).

Nota de seguridadNota de seguridad

No utilice una contraseña en blanco. Utilice una contraseña segura. Para obtener más información, vea Contraseñas seguras.

El mensaje de contraseña se muestra en la consola de la siguiente manera: Password:

La entrada del usuario queda oculta. Esto significa que no se muestra nada y que el cursor permanece en su posición.

La variable de entorno SQLCMDPASSWORD permite establecer una contraseña predeterminada para la sesión actual. Por lo tanto, las contraseñas no tienen que estar codificadas de forma rígida en los archivos por lotes.

En el siguiente ejemplo primero se establece la variable SQLCMDPASSWORD en el símbolo del sistema y, después, se obtiene acceso a la utilidad sqlcmd. En el símbolo del sistema, escriba:

SET SQLCMDPASSWORD= p@a$$w0rd

Nota de seguridadNota de seguridad

La contraseña será visible para cualquiera que pueda ver el monitor del equipo.

En el siguiente símbolo del sistema, escriba:

sqlcmd

Si la combinación de nombre de usuario y contraseña no es correcta, se genera un mensaje de error.

NotaNota

La variable de entorno OSQLPASSWORD se ha conservado por motivos de compatibilidad. La variable de entorno SQLCMDPASSWORD tiene prioridad sobre la variable de entorno OSQLPASSWORD; esto significa que sqlcmd y osql se pueden usar una junto a la otra sin interferencias y que los scripts anteriores seguirán funcionando.

Si se usa la opción -P junto con la opción -E, se genera un mensaje de error.

Si la opción -P va seguida de más de un argumento, se genera un mensaje de error y el programa se cierra.

-S [protocol:]server[\instance_name][,port]

Especifica la instancia de SQL Server a la que hay que conectarse. Establece la variable de scripting de sqlcmd SQLCMDSERVER.

Especifique server_name para conectarse a la instancia predeterminada de SQL Server en ese equipo servidor. Especifique server_name [ \instance_name ] para conectarse a una instancia con nombre de SQL Server en ese equipo servidor. Si no se especifica ningún equipo, sqlcmd se conecta a la instancia predeterminada de SQL Server en el equipo local. Esta opción es necesaria si se ejecuta sqlcmd desde un equipo remoto conectado a la red.

protocol puede ser tcp (TCP/IP), lpc (memoria compartida) o np (canalizaciones con nombre).

Si no especifica server_name [ \instance_name ] al iniciar sqlcmd, SQL Server comprueba si existe la variable de entorno SQLCMDSERVER y la usa.

NotaNota

La variable de entorno OSQLSERVER se ha conservado por motivos de compatibilidad. La variable de entorno SQLCMDSERVER tiene prioridad sobre la variable de entorno OSQLSERVER; esto significa que sqlcmd y osql se pueden usar una junto a la otra sin interferencias y que los scripts anteriores seguirán funcionando.

-Ulogin_id

Es el identificador de inicio de sesión del usuario.

NotaNota

La variable de entorno OSQLUSER está disponible por motivos de compatibilidad con versiones anteriores. La variable de entorno SQLCMDUSER tiene prioridad sobre OSQLUSER. Esto significa que sqlcmd y osql se pueden usar una junto a la otra sin interferencias. También significa que los scripts osql existentes seguirán funcionando.

Si no se especifica la opción -U ni la opción -P, sqlcmd intenta conectarse mediante el modo de autenticación de Microsoft Windows. La autenticación se basa en la cuenta de Windows del usuario que está ejecutando sqlcmd.

Si se usa la opción -U junto con la opción -E (descrita más adelante en este tema), se genera un mensaje de error. Si la opción –U va seguida de más de un argumento, se genera un mensaje de error y el programa se cierra.

-znew_password

Cambiar contraseña:

sqlcmd -U someuser -P s0mep@ssword -z a_new_p@a$$w0rd

-Znew_password

Cambiar contraseña y salir:

sqlcmd -U someuser -P s0mep@ssword -Z a_new_p@a$$w0rd

Input/Output Options

-fcodepage | i:codepage[,o:codepage] | o:codepage[,i:codepage]

Especifica las páginas de códigos de entrada y de salida. El número de página de códigos es un valor numérico que especifica una página de códigos instalada en Windows.

Reglas de conversión de páginas de códigos:

  • Si no se especifica ninguna página de códigos, sqlcmd usará la página de códigos actual para los archivos de entrada y salida, a menos que el archivo de entrada sea un archivo Unicode, en cuyo caso no es necesaria la conversión.

  • sqlcmd reconoce automáticamente los archivos de entrada Unicode "big endian" y "little endian". Si se ha especificado la opción -u, la salida siempre será Unicode "little endian".

  • Si no se especifica ningún archivo de salida, la página de códigos de salida será la página de códigos de la consola. Esto permite que la salida se muestre correctamente en la consola.

  • Si hay varios archivos de entrada, se considera que pertenecen a la misma página de códigos. Los archivos de entrada Unicode y no Unicode pueden ser mixtos.

Escriba chcp en el símbolo del sistema para comprobar la página de códigos de Cmd.exe.

-iinput_file[,input_file2...]

Identifica el archivo que contiene un lote de instrucciones SQL o procedimientos almacenados. Se pueden especificar varios archivos que se leerán y se procesarán en orden. No use ningún espacio entre los nombres de archivo. sqlcmd comprobará primero si todos los archivos especificados existen. Si uno o más archivos no existen, sqlcmd se cerrará. Las opciones -i y -Q/-q se excluyen mutuamente.

Ejemplos de rutas de acceso:

-i C:\<nombreDeArchivo>

-i \\<Servidor>\<RecursoCompartido$>\<nombreDeArchivo>

-i "C:\Una carpeta\<nombreDeArchivo>"

Las rutas de acceso a archivos que contengan espacios deben escribirse entre comillas.

Esta opción se puede usar más de una vez: -i input_file -I I input_file.

-ooutput_file

Identifica el archivo que recibe la salida de sqlcmd.

Si se especifica -u, el archivo especificado en output_file se almacena en formato Unicode. Si el nombre de archivo no es válido, se genera un mensaje de error y sqlcmd se cierra. sqlcmd no admite la escritura simultánea de varios procesos de sqlcmd en el mismo archivo. El archivo de salida estará dañado o será incorrecto. Vea el modificador -f para obtener más información acerca de los formatos de archivo. Este archivo se creará si no existe. Se sobrescribirá cualquier archivo con el mismo nombre que pertenezca a una sesión de sqlcmd anterior. El archivo que se especifica aquí no es el archivo stdout. Si se especifica un archivo stdout, este archivo no se usará.

Ejemplos de rutas de acceso:

-o C:\< nombreDeArchivo>

-o \\<Servidor>\<RecursoCompartido$>\<nombreDeArchivo>

-o "C:\Una carpeta\<nombreDeArchivo>"

Las rutas de acceso a archivos que contengan espacios deben escribirse entre comillas.

-r[0 | 1]

Redirige la salida del mensaje de error a la pantalla (stderr). Si no especifica ningún parámetro o si especifica 0, solo se redirigirán los mensajes de error con un nivel de gravedad 11 o superior. Si especifica 1, toda salida de mensaje, incluida PRINT, se redirigirá. No surte efecto si se usa -o. De forma predeterminada, los mensajes se envían a stdout.

-R

Hace que sqlcmd localice las columnas numericas, de moneda, fecha y hora recuperadas de SQL Server basándose en la configuración regional del cliente. De forma predeterminada, estas columnas se muestran con la configuración regional del servidor.

-u

Especifica que output_file se almacena en formato Unicode, independientemente del formato de input_file.

Opciones de ejecución de consultas

-e

Escribe scripts de entrada en el dispositivo de salida estándar (stdout).

-I

Activa (establece en ON) la opción de conexión SET QUOTED_IDENTIFIER. De forma predeterminada, la opción está establecida en OFF. Para obtener más información, vea SET QUOTED_IDENTIFIER (Transact-SQL).

-q"cmdline query"

Ejecuta una consulta cuando se inicia sqlcmd, pero no cierra sqlcmd cuando finaliza la consulta. Se pueden ejecutar varias consultas delimitadas por punto y coma. Utilice las comillas alrededor de la consulta, como se muestra en el siguiente ejemplo.

En el símbolo del sistema, escriba:

sqlcmd -d AdventureWorks2012 -q "SELECT FirstName, LastName FROM Person.Person WHERE LastName LIKE 'Whi%';"

sqlcmd -d AdventureWorks2012 -q "SELECT TOP 5 FirstName FROM Person.Person;SELECT TOP 5 LastName FROM Person.Person;"

Nota importanteImportante

No use el terminador GO en la consulta.

Si se especifica -b junto con esta opción, sqlcmd se cierra en caso de error. -b se describe más adelante en este tema.

-Q"cmdline query"

Ejecuta una consulta cuando se inicia sqlcmd e inmediatamente después cierra sqlcmd. Se pueden ejecutar varias consultas delimitadas por punto y coma.

Utilice las comillas alrededor de la consulta, como se muestra en el siguiente ejemplo.

En el símbolo del sistema, escriba:

sqlcmd -d AdventureWorks2012 -Q "SELECT FirstName, LastName FROM Person.Person WHERE LastName LIKE 'Whi%';"

sqlcmd -d AdventureWorks2012 -Q "SELECT TOP 5 FirstName FROM Person.Person;SELECT TOP 5 LastName FROM Person.Person;"

Nota importanteImportante

No use el terminador GO en la consulta.

Si se especifica -b junto con esta opción, sqlcmd se cierra en caso de error. -b se describe más adelante en este tema.

-tquery_timeout

Especifica el número de segundos que tienen que transcurrir antes de que un comando (o la instrucción de SQL) exceda el tiempo de espera. Esta opción establece la variable de scripting de sqlcmd SQLCMDSTATTIMEOUT. Si no se especifica ningún valor para time_out, el comando no tiene tiempo de espera. query time_out debe ser un número comprendido entre 1 y 65534. Si el valor proporcionado no es numérico o no está dentro de este intervalo, sqlcmd genera un mensaje de error.

NotaNota

El tiempo de espera real puede variar unos segundos con respecto al valor de time_out especificado.

-vvar = value[ var = value...]

Crea una variable de scripting de sqlcmdque se puede usar en un script de sqlcmd. Si el valor contiene espacios en blanco, especifíquelo entre comillas. Puede especificar varios valores var="values". Si hay errores en alguno de los valores especificados, sqlcmd genera un mensaje de error y después se cierra.

sqlcmd -v MyVar1=something MyVar2="some thing"

sqlcmd -v MyVar1=something -v MyVar2="some thing"

-x

Hace que sqlcmd omita las variables de scripting. Es útil cuando un script contiene muchas instrucciones INSERT que pueden contener cadenas con el mismo formato que las variables normales, por ejemplo, $(variable_name).

Opciones de formato

-hheaders

Especifica el número de filas que se van a imprimir entre los encabezados de las columnas. El valor predeterminado es imprimir los encabezados una vez para cada conjunto de resultados de la consulta. Esta opción establece la variable de scripting de sqlcmd SQLCMDHEADERS. Use -1 para especificar que no desea imprimir los encabezados. Cualquier valor no válido hará que sqlcmd genere un mensaje de error y se cierre.

-k [1 | 2]

Quita todos los caracteres de control, como tabulaciones y nuevos caracteres de línea de la salida. De este modo se conserva el formato de las columnas cuando se devuelven datos. Si se especifica 1, los caracteres de control se reemplazan con un solo espacio. Si se especifica 2, los caracteres de control consecutivos se reemplazan por un solo espacio. -k equivale a -k1.

-scol_separator

Especifica el carácter separador de columnas. El valor predeterminado es un espacio en blanco. Esta opción establece la variable de scripting de sqlcmd SQLCMDCOLSEP. Para usar caracteres que tienen un significado especial para el sistema operativo, como la y comercial (&) o el punto y coma (;), incluya el carácter entre comillas ("). El separador de columnas puede ser cualquier carácter de 8 bits.

-wcolumn_width

Especifica el ancho de pantalla para la salida. Esta opción establece la variable de scripting de sqlcmd SQLCMDCOLWIDTH. El ancho de columna debe ser un número mayor que 8 y menor que 65536. Si el ancho de columna especificado no está en ese intervalo, sqlcmd generará un mensaje de error. El ancho predeterminado es 80 caracteres. Cuando la línea de salida supera el ancho de columna especificado, se ajusta a la siguiente línea.

-W

Esta opción quita los espacios finales de una columna. Use esta opción junto con la opción -s cuando prepare datos que se vayan a exportar a otra aplicación. No se puede usar con las opciones -y ni -Y.

-yvariable_length_type_display_width

Establece la variable de scripting de sqlcmd SQLCMDMAXFIXEDTYPEWIDTH. El valor predeterminado es 256. Limita el número de caracteres que se devuelve para tipos de datos de longitud variable y gran tamaño:

  • varchar(max)

  • nvarchar(max)

  • varbinary(max)

  • xml

  • UDT (user-defined data types)

  • text

  • ntext

  • image

NotaNota

Los UDT pueden ser de longitud fija, en función de la implementación. Si esta longitud de un UDT de longitud fija es más corta que display_width, el valor del UDT devuelto no se ve afectado. No obstante, si la longitud es mayor que display_width, la salida queda truncada.

Si display_width es 0, la salida queda truncada en 1 MB.

Nota importanteImportante

Use la opción -y 0 con mucha precaución, ya que puede causar graves problemas de rendimiento en el servidor y en la red, según el tamaño de los datos devueltos.

-Yfixed_length_type_display_width

Establece la variable de scripting de sqlcmd SQLCMDMAXVARTYPEWIDTH. El valor predeterminado es 0 (ilimitado). Limita el número de caracteres que se devuelve para los siguientes tipos de datos:

  • char(n), donde 1<=n<=8000

  • nchar(nn), donde 1<=n<=4000

  • varchar(nn), donde 1<=n<=8000

  • nvarchar(nn), donde 1<=n<=4000

  • varbinary(nn), donde 1<=n<=4000

  • variant

Opciones de informes de errores

-b

Especifica que sqlcmd se cierre y devuelva un valor de DOS ERRORLEVEL cuando se produce un error. El valor que se devuelve a la variable DOS ERRORLEVEL es 1 cuando el mensaje de error de SQL Server tiene un nivel de gravedad superior a 10; de lo contrario, el valor devuelto es 0. Si se ha establecido la opción -V además de -b, sqlcmd no notificará un error si el nivel de gravedad es inferior a los valores establecidos mediante -V. Los archivos por lotes del símbolo del sistema pueden probar el valor de ERRORLEVEL y controlar el error apropiadamente. sqlcmd no notifica los mensajes de error con un nivel de gravedad de 10 (mensajes informativos).

Si el script de sqlcmd contiene un comentario incorrecto, un error de sintaxis o carece de una variable de scripting, el valor de ERRORLEVEL devuelto es 1.

-merror_level

Controla qué mensajes de error se envían a stdout. Se envían los mensajes que tienen un nivel de gravedad menor o igual que este nivel. Cuando este valor se establece en -1, se envían todos los mensajes, incluidos los informativos. No se permiten espacios entre -m y -1. Por ejemplo, -m-1 es válido, pero -m -1 no lo es.

Esta opción también establece la variable de scripting de sqlcmd SQLCMDERRORLEVEL. El valor predeterminado de esta variable es 0.

-Verror_severity_level

Controla el nivel de gravedad que se usa para establecer la variable ERRORLEVEL. Los mensajes de error que tienen niveles de gravedad menores o iguales que este valor establecen ERRORLEVEL. Los valores menores que 0 se notifican como 0. Los archivos CMD y por lotes se pueden usar para probar el valor de la variable ERRORLEVEL.

Otras opciones

-apacket_size

Solicita un paquete de un tamaño diferente. Esta opción establece la variable de scripting de sqlcmd SQLCMDPACKETSIZE. packet_size debe ser un valor entre 512 y 32767. El valor predeterminado es 4096. Un tamaño de paquete mayor puede mejorar el rendimiento de la ejecución de scripts que comprenden gran cantidad de instrucciones de SQL entre los comandos GO. Puede solicitar un tamaño de paquete mayor. No obstante, si se deniega la solicitud, sqlcmd usa el valor predeterminado de servidor para el tamaño de paquete.

-cbatch_terminator

Especifica el terminador del lote. De forma predeterminada, los comandos se terminan y se envían a SQL Server escribiendo la palabra "GO" en una línea aparte. Cuando restablezca el terminador del lote, no use palabras reservadas de Transact-SQL ni caracteres especiales que tengan un significado especial para el sistema operativo, incluso aunque vayan precedidos de una barra diagonal invertida.

-L[c]

Enumera los equipos servidores configurados localmente y los nombres de los equipos servidores que difunden en la red. Este parámetro no se puede usar en combinación con otros parámetros. El número máximo de equipos de servidor que se puede enumerar es 3000. Si la lista de servidor se trunca debido al tamaño del búfer, aparece un mensaje de advertencia.

NotaNota

Debido a la naturaleza de las difusiones en las redes, sqlcmd podría no recibir una respuesta de todos los servidores a tiempo. Por lo tanto, la lista de servidores devuelta puede variar en cada invocación de esta opción.

Si se especifica el parámetro opcional c, la salida aparece sin lo servidores: la línea de encabezado y cada línea de servidor se muestra sin espacios iniciales. Esto se denomina salida limpia. La salida limpia mejora el rendimiento del procesamiento de los lenguajes de scripting.

-p[1]

Imprime estadísticas de rendimiento para cada conjunto de resultados. A continuación se muestra un ejemplo del formato para las estadísticas de rendimiento:

Network packet size (bytes): n

x xact[s]:

Clock Time (ms.): total t1 avg t2 (t3 xacts per sec.)

Donde:

x indica el número de transacciones que procesa SQL Server.

t1 indica el tiempo total de todas las transacciones.

t2 indica el tiempo medio de una única transacción.

t3 indica el número medio de transacciones por segundo.

Todos los tiempos se indican en milisegundos.

Si se especifica el parámetro opcional 1, el formato de salida de las estadísticas es el separado por dos puntos, que se puede importar fácilmente en una hoja de cálculo o se puede procesar en un script.

Si el parámetro opcional tiene cualquier valor distinto de 1, se genera un error y sqlcmd se cierra.

-X[1]

Deshabilita los comandos que pueden poner en peligro la seguridad del sistema cuando se ejecuta sqlcmd desde un archivo por lotes. Los comandos deshabilitados se siguen reconociendo; sqlcmd emite un mensaje de advertencia y sigue ejecutándose. Si se especifica el parámetro opcional 1, sqlcmd genera un mensaje de error y después se cierra. Los siguientes comandos se deshabilitan cuando se usa la opción -X:

  • ED

  • !! command

Si se especifica la opción -X, eso evita que se pasen variables de entorno a sqlcmd. También impide que el script de inicio especificada mediante la variable de scripting SQLCMDINI se ejecute. Para obtener más información acerca de las variables de scripting de sqlcmd, vea Usar sqlcmd con variables de script.

-?

Muestra el resumen de la sintaxis de las opciones de sqlcmd.

Las opciones no tienen que utilizarse forzosamente en el orden mostrado en la sección de sintaxis.

Cuando se devuelven varios resultados, sqlcmd imprime una línea en blanco entre cada conjunto de resultados de un lote. Además, el mensaje "<x> filas afectadas" no aparece cuando no se aplica a la instrucción ejecutada.

Para usar sqlcmd de forma interactiva, escriba sqlcmd en el símbolo del sistema con una o varias de las opciones descritas anteriormente en este tema. Para obtener más información, vea Usar la utilidad sqlcmd.

NotaNota

Las opciones -L, -Q, -Z o -i hacen que sqlcmd se cierre después de la ejecución.

La longitud total de la línea de comandos de sqlcmd en el entorno de comandos (Cmd.exe), incluidos todos los argumentos y las variables expandidas, es la que determine el sistema operativo para Cmd.exe.

  1. Variables de entorno de nivel de sistema.

  2. Variables de entorno de nivel de usuario.

  3. El shell de comandos (SET X=Y) se establece en el símbolo del sistema antes de ejecutar sqlcmd.

  4. sqlcmd -v X=Y

  5. :Setvar X Y

NotaNota

Para ver las variables de entorno, en el Panel de control, abra Sistema y haga clic en la pestaña Opciones avanzadas.

Variable

Modificador relacionado

L/E

Valor predeterminado

SQLCMDUSER

-U

L

""

SQLCMDPASSWORD

-P

--

""

SQLCMDSERVER

-S

L

"DefaultLocalInstance"

SQLCMDWORKSTATION

-H

L

"ComputerName"

SQLCMDDBNAME

-d

L

""

SQLCMDLOGINTIMEOUT

-l

L/E

"8" (segundos)

SQLCMDSTATTIMEOUT

-t

L/E

"0" = esperar indefinidamente

SQLCMDHEADERS

-h

L/E

"0"

SQLCMDCOLSEP

-s

L/E

" "

SQLCMDCOLWIDTH

-w

L/E

"0"

SQLCMDPACKETSIZE

-a

L

"4096"

SQLCMDERRORLEVEL

-m

L/E

0

SQLCMDMAXVARTYPEWIDTH

-y

L/E

"256"

SQLCMDMAXFIXEDTYPEWIDTH

-Y

L/E

"0" = ilimitado

SQLCMDEDITOR

L/E

"edit.com"

SQLCMDINI

L

""

SQLCMDUSER, SQLCMDPASSWORD y SQLCMDSERVER se establecen cuando se usa :Connect

.

L indica que el valor solo puede establecerse una vez durante la inicialización del programa.

L/E indica que el valor puede modificarse mediante el comando setvar y que los comandos siguientes se verán influidos por el nuevo valor.

Además de las instrucciones Transact-SQL de sqlcmd, también están disponibles los siguientes comandos:

GO [count]

:List

[:] RESET

:Error

[:] ED

:Out

[:] !!

:Perftrace

[:] QUIT

:Connect

[:] EXIT

:On Error

:r

:Help

:ServerList

:XML [ON | OFF]

:Setvar

:Listvar

Tenga en cuenta lo siguiente cuando use comandos de sqlcmd:

  • Todos los comandos de sqlcmd, excepto GO, deben ir precedidos de dos puntos (:).

    Nota importanteImportante

    Para mantener la compatibilidad con los scripts de osql existentes, algunos de los comandos se reconocerán sin los dos puntos. Esto está indicado por [:].

  • Los comandos de sqlcmd se reconocen solo si aparecen al principio de una línea.

  • Los comandos de sqlcmd no distinguen entre mayúsculas y minúsculas.

  • Cada comando debe estar en una línea separada. Un comando no puede ir seguido de una instrucción de Transact-SQL o de otro comando.

  • Los comandos se ejecutan inmediatamente. No se colocan en el búfer de ejecución, como es el caso de las instrucciones Transact-SQL.

Editar comandos

[:] ED

Inicia el editor de texto. Este editor se puede utilizar para editar el lote actual de Transact-SQL o el último lote ejecutado. Para editar el último lote ejecutado, el comando ED debe escribirse inmediatamente después de que se complete la ejecución del último lote.

El editor de texto se define mediante la variable de entorno SQLCMDEDITOR. El editor predeterminado es "Edit". Para cambiar el editor, establezca la variable de entorno SQLCMDEDITOR. Por ejemplo, para establecer el editor en el Bloc de notas de Microsoft, en el símbolo del sistema, escriba:

SET SQLCMDEDITOR=notepad

[:] RESET

Borra la caché de instrucciones.

:List

Imprime el contenido de la memoria caché de instrucciones.

Variables

:Setvar <var> [ "value" ]

Define las variables de scripting de sqlcmd. Las variables de scripting tienen el siguiente formato: $(VARNAME).

Los nombres de variables no distinguen entre mayúsculas y minúsculas.

Las variables de scripting pueden establecerse de los siguientes modos:

  • Implícitamente mediante una opción de línea de comandos. Por ejemplo, la opción -l establece la variable de sqlcmd SQLCMDLOGINTIMEOUT.

  • Explícitamente mediante el comando :Setvar.

  • Al definir una variable de entorno antes de ejecutar sqlcmd.

NotaNota

La opción -X impide que las variables de entorno se pasen a sqlcmd.

Si una variable definida mediante :Setvar y una variable de entorno tienen el mismo nombre, la variable definida mediante :Setvar tiene prioridad.

Los nombres de variables no deben contener caracteres de espacio en blanco.

Los nombres de variable no pueden tener el mismo formato que una expresión variable como $(var).

Si el valor de la cadena de la variable de script contiene espacios en blanco, incluya el valor entre comillas. Si un valor para la variable del script no se especifica, la variable de script se elimina.

:Listvar

Muestra una lista de variables de scripting que están establecidas actualmente.

NotaNota

Solo se mostrarán las variables de scripting establecidas mediante sqlcmd y las variables establecidas con el comando :Setvar.

Comandos de salida

:Error <filename>|STDERR|STDOUT

Redirige toda la salida de error al archivo especificado por file name, a stderr o a stdout. El comando Error puede aparecer varias veces en un script. De forma predeterminada, la salida de error se envía a stderr.

file name

Crea y abre un archivo que recibirá la salida. Si el archivo ya existe, se truncará en cero bytes. Si el archivo no está disponible a causa de los permisos u otros motivos, la salida no se cambiará y se enviará al último destino especificado o al predeterminado.

STDERR

Cambia la salida del error al flujo stderr. Si se ha redirigido, el destino al cual se redirige el flujo recibirá la salida del error.

STDOUT

Cambia la salida del error al flujo stdout. Si se ha redirigido, el destino al cual se redirige el flujo recibirá la salida del error.

:Out <filename>| STDERR| STDOUT

Crea y redirige todos los resultados de consulta al archivo especificado por file name, a stderr o a stdout. De forma predeterminada, la salida se envía a stdout. Si el archivo ya existe, se truncará en cero bytes. El comando Out puede aparecer varias veces en un script.

:Perftrace <filename>| STDERR| STDOUT

Crea y redirige toda la información de seguimiento de rendimiento al archivo especificado por file name, a stderr o a stdout. De forma predeterminada, la salida de seguimiento de rendimiento se envía a stdout. Si el archivo ya existe, se truncará en cero bytes. El comando Perftrace puede aparecer varias veces en un script.

Comandos de control de ejecución

:On Error[ exit | ignore]

Establece la acción que se llevará a cabo cuando se produzca un error durante la ejecución del script o del lote.

Cuando se usa la opción exit, sqlcmd se cierra con el valor de error correspondiente.

Cuando se usa la opción ignore, sqlcmd pasa por alto el error y continúa con la ejecución del lote o del script. De forma predeterminada, se imprimirá un mensaje de error.

[:] QUIT

Hace que sqlcmd se cierre.

[:] EXIT[ (statement) ]

Permite usar el resultado de una instrucción SELECT como valor devuelto de sqlcmd. Si es numérica, la primera columna de la última fila del resultado se convierte en un entero de 4 bytes (long). MS-DOS pasa el byte bajo al proceso primario o al nivel de errores del sistema operativo. Windows 200x pasa el entero de 4 bytes completo. La sintaxis es:

:EXIT(query)

Por ejemplo:

:EXIT(SELECT @@ROWCOUNT)

También puede incluir el parámetro EXIT como parte de un archivo por lotes. Por ejemplo, en el símbolo del sistema, escriba:

sqlcmd -Q "EXIT(SELECT COUNT(*) FROM '%1')"

La utilidad sqlcmd envía todo lo que está entre paréntesis ( ) al servidor. Si un procedimiento almacenado del sistema selecciona un conjunto y devuelve un valor, solo se devuelve la selección. La instrucción EXIT( ) sin nada entre los paréntesis ejecuta todo lo que precede a estos en el lote y, a continuación, se cierra sin ningún valor devuelto.

Cuando se especifica una consulta incorrecta, sqlcmd se cierra sin devolver ningún valor.

Aquí se muestra una lista de formatos de EXIT:

  • :EXIT

No ejecuta el lote y, después, sale de forma inmediata y no devuelve ningún valor.

  • :EXIT( )

Ejecuta el lote y, a continuación, sale sin devolver ningún valor.

  • :EXIT(query)

Ejecuta el lote que incluye la consulta y, a continuación, se cierra tras devolver el resultado de la consulta.

Si se usa RAISERROR en un script de sqlcmd y se genera el estado 127, sqlcmd se cerrará y devolverá un identificador de mensaje al cliente. Por ejemplo:

RAISERROR(50001, 10, 127)

Este error hará que el script de sqlcmd finalice y devuelva el identificador de mensaje 50001 al cliente.

Los valores devueltos -1 a -99 están reservados para SQL Server; sqlcmd define los siguientes valores devueltos adicionales:

Valores devueltos

Descripción

-100

Error encontrado antes de seleccionar el valor devuelto.

-101

No se encontró ninguna fila al seleccionar el valor devuelto.

-102

Error de conversión al seleccionar el valor devuelto.

GO [count]

GO marca tanto el final de un lote como la ejecución de cualquier instrucción de Transact-SQL almacenada en caché. Cuando especifique un valor para count, las instrucciones almacenadas en caché se ejecutarán tantas veces como indique count, como un solo lote.

Otros comandos

:r <filename>

Analiza instrucciones Transact-SQL y comandos sqlcmd adicionales desde el archivo especificado por <filename> en la memoria caché de instrucciones.

Si el archivo contiene instrucciones Transact-SQL que no van seguidas de GO, debe escribir GO en la línea que sigue a :r.

NotaNota

<filename> se lee de forma relativa al directorio de inicio en el que se ejecutó sqlcmd.

El archivo se leerá y se ejecutará después de que se encuentre un terminador de lote. Puede emitir varios comandos :r. El archivo puede incluir cualquier comando de sqlcmd. Eso incluye el terminador de lote GO.

NotaNota

El recuento de líneas que se muestra en el modo interactivo aumentará en uno por cada comando :r que se encuentre. El comando :r aparecerá en la salida del comando de lista.

:Serverlist

Enumera los servidores configurados localmente y los nombres de los servidores que difunden en la red.

:Connect server_name[\instance_name] [-l timeout] [-U user_name [-P password]]

Conecta con una instancia de SQL Server. También cierra la conexión actual.

Opciones de tiempo de espera:

0

espera indefinidamente

n>0

espera durante n segundos

La variable de scripting SQLCMDSERVER reflejará la conexión activa actual.

Si no se especifica timeout, el valor de la variable SQLCMDLOGINTIMEOUT es el predeterminado.

Si solo se especifica user_name (como opción o como variable de entorno), se solicitará al usuario que especifique una contraseña. Esto no es así si se han establecido las variables de entorno SQLCMDUSER o SQLCMDPASSWORD. Si no se proporcionan opciones ni variables de entorno, se iniciará sesión en modo Autenticación de Windows. Por ejemplo, para conectar con una instancia, instance1, de SQL Server, myserver, mediante seguridad integrada, se necesitaría lo siguiente:

:connect myserver\instance1

Para conectar con la instancia predeterminada de myserver con variables de script, utilizaría lo siguiente:

:setvar myusername test

:setvar myservername myserver

:connect $(myservername) $(myusername)

[:] !!< command>

Ejecuta comandos del sistema operativo. Para ejecutar un comando del sistema operativo, inicie una línea con dos signos de exclamación (!!) seguidos por el comando del sistema operativo. Por ejemplo:

:!! Dir

NotaNota

El comando se ejecuta en el equipo en el que se ejecuta sqlcmd.

:XML [ON | OFF]

Para obtener más información, vea "Formato de salida XML", más adelante en este tema

:Help

Muestra los comandos de sqlcmd junto con una breve descripción de cada comando.

Nombres de archivo de sqlcmd

Los archivos de entrada de sqlcmd se pueden especificar con la opción -i o con el comando :r. Los archivos de salida se pueden especificar con la opción -o o con los comandos :Error, :Out y :Perftrace. A continuación se incluyen algunas directrices para trabajar con estos archivos:

  • :Error, :Out y :Perftrace deben usar valores de <filename> independientes. Si se utiliza el mismo <filename>, es posible que las entradas de los comandos se entremezclen.

  • Si sqlcmd llama a un archivo de entrada ubicado en un servidor remoto desde un equipo local y el archivo contiene una ruta de acceso de archivo del tipo :out c:\archivoDeSalida.txt. el archivo de salida se creará en el equipo local y no en el servidor remoto.

  • Entre las rutas de archivo válidas se incluyen: C:\<filename>, \\<Servidor>\<RecursoCompartido$>\<filename> y "C:\Una carpeta\<file name>". Si hay algún espacio en blanco en la ruta de acceso, use comillas.

  • Cada nueva sesión de sqlcmd sobrescribirá los archivos existentes que tengan el mismo nombre.

Mensajes informativos

sqlcmd imprime los mensajes informativos enviados por el servidor. En el siguiente ejemplo, tras ejecutar las instrucciones de Transact-SQL, se imprime un mensaje informativo.

En el símbolo del sistema, escriba lo siguiente:

sqlcmd

At the sqlcmd prompt type:

USE AdventureWorks2012;

GO

Cuando se presiona ENTRAR, se imprime el siguiente mensaje informativo: "Se cambió el contexto de la base de datos a 'AdventureWorks2008R2'".

Formato de salida de consultas de Transact-SQL

sqlcmd primero imprime un encabezado de columna que contiene los nombres de columna especificados en la lista de selección. Los nombres de columna se separan mediante el carácter SQLCMDCOLSEP. De forma predeterminada, es un espacio en blanco. Si el nombre de la columna es más corto que el ancho de la columna, la salida se rellena con espacios hasta la siguiente columna.

Esta línea irá seguida de una línea separadora, que es una serie de caracteres de guión. La siguiente salida muestra un ejemplo.

Inicie sqlcmd. En el símbolo del sistema de sqlcmd, escriba lo siguiente:

USE AdventureWorks2012;

SELECT TOP (2) BusinessEntityID, FirstName, LastName

FROM Person.Person;

GO

Cuando presione ENTRAR, se devolverá el siguiente conjunto de resultados.

BusinessEntityID FirstName    LastName

---------------- ------------ ----------

285              Syed         Abbas

293              Catherine    Abel

(2 row(s) affected)

Aunque la columna BusinessEntityID tiene solo 4 caracteres de ancho, se ha expandido para acomodar el nombre de columna más largo. De forma predeterminada, la salida finaliza a los 80 caracteres. Esto se puede cambiar mediante la opción -w o al establecer la variable de scripting SQLCMDCOLWIDTH.

Formato de salida XML

La salida XML de una cláusula FOR XML se ofrece sin formato en un flujo continuo.

Cuando espere una salida XML, use el siguiente comando: :XML ON.

NotaNota

sqlcmd devuelve mensajes de error en el formato habitual. Tenga en cuenta que los mensajes de error también salen en el flujo de texto XML en formato XML. Con :XML ON, sqlcmd no muestra mensajes informativos.

Para desactivar el modo XML, use el siguiente comando: :XML OFF.

El comando GO no debe aparecer antes de que se emita el comando XML OFF, ya que el comando XML OFF vuelve a cambiar sqlcmd a la salida orientada a filas.

Los datos XML (de flujo) y los datos del conjunto de filas no se pueden mezclar. Si el comando XML ON no se ha emitido antes de ejecutar una instrucción Transact-SQL que genera flujos XML, la salida será confusa. Si se ha emitido el comando XML ON, no se pueden ejecutar instrucciones Transact-SQL que den como resultado conjuntos de filas normales.

NotaNota

El comando :XML no admite la instrucción SET STATISTICS XML.

Use las siguientes prácticas para maximizar la seguridad y la eficacia.

  • Use seguridad integrada.

  • Use -X en los entornos automatizados.

  • Proteja los archivos de entrada y salida mediante los permisos del sistema de archivos NTFS adecuados.

  • Para aumentar el rendimiento, haga tanto como pueda en una sola sesión de sqlcmd en vez de emplear varias.

  • Establezca valores de tiempo de espera para la ejecución de lotes y consultas superiores a los que prevea para la ejecución de cada lote o consulta.

Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Temas legales | Marcas Registradas | Declaración de privacidad
Page view tracker