method to invoke SQL by batch (osql) _dos/bat

Source: Internet
Author: User
Tags microsoft sql server odbc
osql/u alma/p/I Stores.bat
(Stores.bat contains the update, DELETE statement, but no go is required)
----------------------------------------------------
osql Utility Tool
The osql utility allows you to enter Transact-SQL statements, system procedures, and script files. The utility communicates with the server through ODBC.
Grammar
osql
[-?] ¦
[-l]¦
[
{
{-U login_id [p password]}
¦-e
}
[-S Server_name[instance_name]] [H Wksta_name] [-D db_name]
[-L Time_out] [-T Time_out] [H Headers]
[-S Col_separator] [-W Column_width] [-A packet_size]
[-E] [-I.] [-D Data_source_name]
[-C Cmd_end] [-Q "Query"] [-Q "Query"]
[-N] [M Error_level] [-R {0¦1}]
[I. Input_file] [-O output_file] [-P]
[b] [-u] [-R] [-O]
]
Parameters-?
Displays a syntax summary for the osql switch.
-L
Lists the servers that are configured locally and the names of the servers that are broadcast on the network.
-U login_id
User Login ID. The login ID is case-sensitive.
-p password
is the password specified by the user. If the-P option is not used, osql prompts for a password. If you use the-P option at the end of the command prompt with no password, osql uses the default password (NULL). Passwords are case-sensitive.
The OSQLPASSWORD environment variable allows you to set the default password for the current session. Therefore, you do not need to hard-code to set a password in a batch file.
If you do not specify a password for the-P option, osql first checks the Osqlpassword variable. If the value is not set, osql uses the default password (NULL). The following example sets the Osqlpassword variable at a command prompt and then accesses the osql utility:
C:>set Osqlpassword=abracadabra
C:>osql
-E
Use a trusted connection without requesting a password.
-S Server_name[instance_name]
Specifies the Microsoft®sql server™2000 instance to connect to. Specify server_name on this server to connect to the default instance of SQL Server. Specify server_nameinstance_name on this server to connect to an instance of a named SQL Server 2000. If you do not specify a server, osql connects to the default instance of SQL Server on the local computer. This option is required when performing osql from a remote computer on the network.
-H Wksta_name
is the workstation name. The workstation name is stored in Sysprocesses.hostname and is displayed by sp_who. If this option is not specified, the current computer name is used.
-D db_name
A use DB_NAME statement is issued when the osql is started.
-L Time_out
Specifies the number of seconds before the osql logon timeout. The default timeout for logging on to osql is 8 seconds.
-T Time_out
Specifies the number of seconds before the command times out. If you do not specify a time_out value, the command does not timeout.
-H Headers
Specifies the number of rows to print between column headings. The default is to print a title once for each query result set. Specifies that the title is not printed with –1. If you use-1, there must be no spaces between the parameters and settings (can be-h-1, not-h–1).
-S Col_separator
Specifies the column separator character, which is assumed to be a space. To use characters that have special meaning to the operating system (for example, ¦; & < >), enclose the character in double quotes (").
-W Column_width
Allows the user to set the width of the screen output. The default is 80 characters. When the output line reaches its maximum screen width, it is split into multiple rows.
-A packet_size
Enables you to request packets of different sizes. The valid values for packet_size are between 512 and 65535. The default value for osql is the default value for the server. The increase in packet size increases the performance of larger script execution, in which the number of SQL statements between GO commands is important. Microsoft tests show that 8192 is the fastest setting typical for bulk copy operations. You can request a larger packet size, but if the request cannot be approved, osql defaults to the server's default value.
-E
echo input.
-I.
Set the QUOTED_IDENTIFIER connection option to open.
-D Data_source_name
Connect to an ODBC data source that is defined with an ODBC driver for Microsoft SQL Server. The osql connection uses the options specified in the data source.

Indicates that this option does not apply to data sources defined by other drivers.

-C Cmd_end
Specifies the command terminator. By default, the command is terminated and sent to SQL Server 2000 by entering go alone on a single line. When you reset a command terminator, do not use Transact-SQL reserved words or characters that have special meaning to the operating system, regardless of whether there is a backslash before it.
-Q "Query"
Executes the query when the osql is started, but does not exit osql when the query completes. (Note that the query statement should not contain go). If you are issuing a query from a batch file, use either%variables or the environment%variables%. For example:
SET table = sysobjects
osql/q "SELECT * from%table%"
Enclose the query in double quotes to enclose any content embedded in the query in single quotes.
-Q "Query"
Execute the query and exit osql immediately. Enclose the query in double quotes to enclose any content embedded in the query in single quotes.
-N
Deletes the number and hint symbol (>) from the input line.
-M Error_level
The display of custom error messages. Displays the number of messages, status, and error levels for the specified or higher severity level error. does not display any information about errors with a severity level below the specified level. Use 1 To specify that all headers, even messages of information classes, be returned with the message. If you use –1, there can be no spaces between the parameters and the settings (-m-1, not-m-1).
-R {0¦1}
Redirects the message output to the screen (stderr). If you do not specify a parameter, or if you specify a parameter of 0, only error messages with a severity level of 17 or higher are redirected. If the specified parameter is 1, all message output (including "print") is redirected.
-I. Input_file
Identifies a file that contains a batch of SQL statements or stored procedures. Less than (<) comparison operators can be used instead of – I.
-O output_file
Identifies the file that receives output from osql. The greater than (>) comparison operator can be used instead of –o.
If Input_file is not Unicode and you do not specify-u, output_file is stored as an OEM format. If Input_file is Unicode or-U is specified, output_file is stored in Unicode format.
-P
Print performance statistics.
-B
Specifies that osql exits and returns a DOS ERRORLEVEL value when an error occurs. When the severity level of the SQL Server error message is 10 or higher, the value returned to the DOS errorlevel variable is 1; otherwise, 0 is returned. Microsoft ms-dos® Batch files can test the values of DOS errorlevel and handle errors appropriately.
-U
Specifies that output_file is stored in Unicode format, regardless of input_file format.
-R
Specifies that the SQL Server ODBC driver uses client settings when converting currency, date, and time data to character data.
-O
Specifies that some osql features are deactivated to match the earlier version behavior of the isql. The following features are disabled:
EOF Batch Processing

Automatic Console width adjustment

Wide information
The default value for DOS ERRORLEVEL is also set to –1.
Comments
The osql utility starts directly from the operating system and uses the case-sensitive options listed in this article. Once started, osql accepts the SQL statements and sends them interactively to SQL Server. The results are formatted and displayed on the screen (stdout). You can use QUIT or exit to exit osql.
If you do not specify a user name when you start osql, SQL Server 2000 checks the environment variables and uses them, such as osqluser= (user) or osqlserver= (server). If the environment variable is not set, the workstation user name is used. If no server is specified, the workstation name is used.
If the-U or-P option is not used, SQL Server 2000 attempts to connect using Windows authentication mode. Authentication is based on the Microsoft Windows NT® user account that is running osql.
The osql utility uses the ODBC API. The utility uses the SQL Server-SQL-92 connection option by using the default settings for the ODBC driver. For more information, see the effect of the SQL-92 option.
For information about the location and how this utility works, see Getting Started with the command prompt utility.
OSQL command
In addition to Transact-SQL statements used in osql, the commands in the following table are also available.
Command description
Go executes all statements entered after the last go command.
RESET clears all the statements that have been entered.
ED invokes the editor.
!! command to execute operating system commands.
QUIT or exit () exits osql.
CTRL + C key does not exit osql and ends the query.

This can only be recognized when the command Terminator Go (default), RESET, ED 、!!、 EXIT, QUIT, and CTRL + C appear at the beginning of a line (immediately following the osql prompt). osql ignores any content entered after these keywords in the same row.
Go indicates the end of a batch and any execution of a Transact-SQL statement that has been cached. When you press the ENTER key at the end of each input line, osql caches the statement for the row. When you press ENTER after you type go, all currently cached statements are sent as batches to SQL Server.
The current osql utility works as if there is an implied go at the end of any executed script, so all statements in the script are executed. Any statements after the last go are not executed.
Ends a command by typing a line that starts with a command terminator. You can specify the number of times the command will run by entering an integer after the command terminator. For example, to execute this command 100 times, type:
SELECT x = 1
Go 100
Prints a result at the end of execution. osql does not accept results of more than 1,000 characters per line. Long statements should be written across multiple lines.
By typing ED at the beginning of the line, the user can invoke the editor on the current query buffer. The editor is defined in the EDITOR environment variable. The default editor is "edit". You can specify other editors by setting the EDITOR environment variable. For example, to designate the default editor as Notepad, at the operating system prompt, enter:
SET Editor=notepad
Operating system commands
You can also execute operating system commands by starting a line with two exclamation points (!!) and then entering a command. The command recall feature of Windows NT can be used to recall and modify osql statements. Type RESET to clear the existing query buffer.
When you run a stored procedure, osql prints a blank line between each result set in the batch. In addition, if no statements are applied to the executed statement, the "0 rows affected" message does not appear.
Interactive use of osql
To use osql interactively, type the osql command (and any options) at the command prompt.
You can read in a file that contains a query executed by osql (for example, stores.qry) by typing a command similar to the following:
osql/u alma/p/I Stores.qry
The file must contain a command terminator.
You can read in a file that contains a query (for example, titles.qry) by typing a command that resembles a line, and then directing the result to another file:
osql/u alma/p/I titles.qry/o titles.res
When using osql interactively, to read the operating system files into the command buffer, you can use: R file_name. Do not include a command terminator in the file, and interactively enter the Terminator after the edit is complete.
Inserting comments
You can include comments in Transact-SQL statements that osql submits to SQL Server. Two annotation style types are allowed:--and/*...*/.
For more information, see Working with annotations.
Use EXIT to return osql results
You can use the result of the SELECT statement as the return value of the osql. The first column of the first result row is converted to a 4-byte integer (Long Integer). MS-DOS passes low bytes to the parent process or operating system error level. Windows NT passes the entire 4-byte integer. The syntax is:
EXIT (query)
For example:
EXIT (SELECT @ @ROWCOUNT)
EXIT (SELECT 5)
You can also include the EXIT parameter to make it part of a batch file. For example:
osql/q "EXIT (SELECT COUNT (*) from '%1 ')"
The osql utility passes all the content entered in parentheses () to the server as-is. If the storage system procedure selects a set merge to return a value, only the selected content is returned. The exit () statement with no arguments between parentheses executes all the content before this statement in the batch, and then exits without returning a value.
The EXIT format has four types:
EXIT
Exits immediately without performing a batch, with no return value.
EXIT ()
Exit after batch processing, no return value.
EXIT (query)
Executes the batch that includes the query, returns the result of the query, and exits.
RAISERROR with a status of 127.
If you use RAISERROR in the osql script and a status of 127 appears, osql quits and returns the message ID to the client. For example:
RAISERROR (50001, 10, 127)
This error causes the osql script to terminate and return message ID 50001 to the client program.
SQL Server retains the return value between 1 and 99; osql defines the following values:
-100
The error encountered before selecting the return value.
-101
The row was not found when the return value was selected.
-102
A conversion error occurred while selecting the return value.
Show money and smallmoney data types
OSQL Displays the money and smallmoney data types with only two-bit decimal digits, but SQL Server stores the values of both types of data internally with four-bit decimal digits. Take a look at the following example:
SELECT cast (CAST (10.3496 as) as decimal (6, 4))
The result of this statement is 10.3496, which indicates that the value is stored as is in the complete decimal place.
'----------------------------------------------------------------------------------------------------------
Keep your statement in a. sql file first.
And then, in the. bat file, write this

osql-s [Server]-u [user name]-p [Password]-d [Database]-n-i [. sql file]
Remove the brackets

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.