Microsoft.Data.SqlClient
This exception is thrown when an ongoing operation is aborted by the user.
event sets the **Abort** property to `true` in the object passed to the handler, the method stops sending rows to the server and throws an .
]]>
Represents a request for notification for a given command.
class provides a simpler way of using query notifications. However, if you need fine control over when notifications occur, or you need to customize the message data returned as part of a notification, the class is the one to use.
]]>
Using Query Notifications
Creates a new instance of the class with default values.
object, that instance must have its and properties initialized before assigning the object to a object's property. The default values used by the constructor are NULL (`Nothing` in Visual Basic) for the , an empty string for the , and zero for the .
]]>
Using Query Notifications
A string that contains an application-specific identifier for this notification. It is not used by the notifications infrastructure, but it allows you to associate notifications with the application state. The value indicated in this parameter is included in the Service Broker queue message.A string that contains the Service Broker service name where notification messages are posted, and it must include a database name or a Service Broker instance GUID that restricts the scope of the service name lookup to a particular database. For more information about the format of the parameter, see .The time, in seconds, to wait for a notification message.Creates a new instance of the class with a user-defined string that identifies a particular notification request, the name of a predefined SQL Server 2005 Service Broker service name, and the time-out period, measured in seconds.
instance, providing your own identifier, the SQL Server 2005 Service Broker service name, and a time-out value.
]]>
The value of the parameter is NULL.The or parameter is longer than or the value in the parameter is less than zero.Using Query Notifications
Gets or sets the SQL Server Service Broker service name where notification messages are posted.
that contains the SQL Server 2005 Service Broker service name where notification messages are posted and the database or service broker instance GUID to scope the server name lookup.
property has the following format:
`service={;(local database=|broker instance=)}`
For example, if you use the service "myservice" in the database "AdventureWorks" the format is:
`service=myservice;local database=AdventureWorks`
The SQL Server Service Broker service must be previously configured on the server. In addition, a Service Broker service and queue must be defined and security access granted as needed. See the SQL Server 2005 documentation for more information.
]]>
The value is NULL.The value is longer than .Using Query Notifications
Gets or sets a value that specifies how long SQL Server waits for a change to occur before the operation times out.A signed integer value that specifies, in seconds, how long SQL Server waits for a change to occur before the operation times out.
property defaults to the value set on the server.
]]>
The value is less than zero.Using Query Notifications
Gets or sets an application-specific identifier for this notification.A value of the application-specific identifier for this notification.
property is included in the SQL Server 2005 queue message.
]]>
The value is longer than .Using Query Notifications
Provides a mechanism for enumerating all available instances of SQL Server within the local network.
class exposes this information to the application developer, providing a containing information about all the available servers. This returned table contains a list of server instances that matches the list provided when a user attempts to create a new connection, and on the `Connection Properties` dialog box, expands the drop-down list containing all the available servers.
]]>
Enumerating Instances of SQL Server
Gets an instance of the , which can be used to retrieve information about available SQL Server instances.An instance of the used to retrieve information about available SQL Server instances.
class does not provide a constructor. Use the property to retrieve an instance of the class instead.
[!code-csharp[SqlDataSourceEnumeratorExample#1](~/../sqlclient/doc/samples/SqlDataSourceEnumeratorExample.cs#1)]
## Examples
The following console application displays a list of all the available SQL Server 2005 instances within the local network. This code uses the method to filter the rows in the table returned by the method.
[!code-csharp[SqlDataSourceEnumeratorVersionExample#1](~/../sqlclient/doc/samples/SqlDataSourceEnumeratorVersionExample.cs#1)]
]]>
Enumerating Instances of SQL Server
Retrieves a containing information about all visible SQL Server instances.A containing information about the visible SQL Server instances.
10.0.xx for SQL Server 2008
10.50.x for SQL Server 2008 R2
11.0.xx for SQL Server 2012
12.0.xx for SQL Server 2014
13.0.xx for SQL Server 2016
14.0.xx for SQL Server 2017|
> [!NOTE]
> Due to the nature of the mechanism used by to locate data sources on a network, the method will not always return a complete list of the available servers, and the list might not be the same on every call. If you plan to use this function to let users select a server from a list, make sure that you always also supply an option to type in a name that is not in the list, in case the server enumeration does not return all the available servers. In addition, this method may take a significant amount of time to execute, so be careful about calling it when performance is critical.
## Examples
The following console application retrieves information about all the visible SQL Server instances and displays the information in the console window.
[!code-csharp[SqlDataSourceEnumerator.Example#1](~/../sqlclient/doc/samples/SqlDataSourceEnumeratorExample.cs#1)]
]]>
Enumerating Instances of SQL Server
Exposes SQL Server data that is stored with the FILESTREAM column attribute as a sequence of bytes.
class is used to work with `varbinary(max)` data stored with the FILESTREAM attribute in a SQL Server 2008 database. You must install the .NET Framework 3.5 SP1 (or later) to use to work with FILESTREAM data.
Specifying the FILESTREAM attribute on a `varbinary(max)` column causes SQL Server to store the data in the local NTFS file system instead of in the database file. Transact-SQL statements provide data manipulation capabilities within the server, and Win32 file system interfaces provide streaming access to the data.
> [!NOTE]
> Individual files stored in a FILESTREAM column cannot be opened directly from the NTFS file system. Streaming FILESTREAM data works only in the context of a SQL Server transaction.
The class is derived from the class, which represents an abstraction of a sequence of bytes from some arbitrary data source such as a file or a block of memory. You can read from a FILESTREAM by transferring data from a stream into a data structure such as an array of bytes. You can write to a FILESTREAM by transferring the data from a data structure into a stream. You can also seek within the stream, which allows you to query and modify data at the current position within the stream.
For conceptual documentation and code examples, see [FILESTREAM Data](/sql/connect/ado-net/sql/filestream-data).
For documentation about setting up and configuring FILESTREAM data on SQL Server, see [Designing and Implementing FILESTREAM Storage](https://go.microsoft.com/fwlink/?LinkId=121499) in SQL Server 2008 Books Online.
]]>
FILESTREAM Data in SQL Server 2008 (ADO.NET)SQL Server Data Type Mappings (ADO.NET)SQL Server Binary and Large-Value Data (ADO.NET)
The logical path to the file. The path can be retrieved by using the Transact-SQL Pathname function on the underlying FILESTREAM column in the table.The transaction context for the object. Applications should return the byte array returned by calling the GET_FILESTREAM_TRANSACTION_CONTEXT method.The access mode to use when opening the file. Supported enumeration values are , , and .
When using , the object can be used to read all of the existing data.
When using , points to a zero byte file. Existing data will be overwritten when the object is closed and the transaction is committed.
When using , the points to a file which has all the existing data in it. The handle is positioned at the beginning of the file. You can use one of the methods to move the handle position within the file to write or append new data.Initializes a new instance of the class.
|
|Write||
|ReadWrite| and |
For more information about CAS, see [Code Access Security and ADO.NET](/dotnet/framework/data/adonet/code-access-security).
If an exception is thrown, any open transactions should be rolled back. Otherwise, data loss can occur.
]]>
is a null reference, or is null.
is an empty string (""), contains only white space, or contains one or more invalid characters.
begins with "\\\\.\\", for example "\\\\.\PHYSICALDRIVE0 ".
The handle returned by the call to NTCreateFile is not of type FILE_TYPE_DISK.
contains an unsupported value.The file cannot be found.An I/O error occurred.The caller does not have the required permission.The specified is invalid, such as being on an unmapped drive.The access requested is not permitted by the operating system for the specified path. This occurs when Write or ReadWrite access is specified, and the file or directory is set for read-only access.NtCreateFile fails with error code set to ERROR_SHARING_VIOLATION.FILESTREAM Data in SQL Server 2008 (ADO.NET)
The logical path to the file. The path can be retrieved by using the Transact-SQL Pathname function on the underlying FILESTREAM column in the table.The transaction context for the object. When set to null, an implicit transaction will be used for the object. Applications should return the byte array returned by calling the GET_FILESTREAM_TRANSACTION_CONTEXT method.The access mode to use when opening the file. Supported enumeration values are , , and .
When using , the object can be used to read all of the existing data.
When using , points to a zero byte file. Existing data will be overwritten when the object is closed and the transaction is committed.
When using , the points to a file which has all the existing data in it. The handle is positioned at the beginning of the file. You can use one of the methods to move the handle position within the file to write or append new data.Specifies the option to use while opening the file. Supported values are , , , and .The allocation size to use while creating a file. If set to 0, the default value is used.Initializes a new instance of the class.
|
|Write||
|ReadWrite| and |
For more information about CAS, see [Code Access Security and ADO.NET](/dotnet/framework/data/adonet/code-access-security).
If an exception is thrown, any open transactions should be rolled back. Otherwise, data loss can occur.
]]>
is a null reference, or is null.
is an empty string (""), contains only white space, or contains one or more invalid characters.
begins with "\\\\.\\", for example "\\\\.\PHYSICALDRIVE0 "
The handle returned by call to NTCreateFile is not of type FILE_TYPE_DISK.
contains an unsupported value.The file cannot be found.An I/O error occurred.The caller does not have the required permission.The specified is invalid, such as being on an unmapped drive.The access requested is not permitted by the operating system for the specified path. This occurs when Write or ReadWrite access is specified, and the file or directory is set for read-only access.NtCreateFile fails with error code set to ERROR_SHARING_VIOLATION.FILESTREAM Data in SQL Server 2008 (ADO.NET)
Gets the logical path of the passed to the constructor.A string value indicating the name of the .To be added.FILESTREAM Data in SQL Server 2008 (ADO.NET)
Gets or sets the transaction context for this object.The array that was passed to the constructor for this object.To be added.FILESTREAM Data in SQL Server 2008 (ADO.NET)
Gets a value indicating whether the current stream supports reading.
if the current stream supports reading; otherwise, .To be added.FILESTREAM Data in SQL Server 2008 (ADO.NET)
Gets a value indicating whether the current stream supports seeking.
if the current stream supports seeking; otherwise, .To be added.FILESTREAM Data in SQL Server 2008 (ADO.NET)
Gets a value indicating whether the current stream can time out.
if the current stream can time out; otherwise, .To be added.
Gets a value indicating whether the current stream supports writing.
if the current stream supports writing; otherwise, .To be added.FILESTREAM Data in SQL Server 2008 (ADO.NET)
Gets a value indicating the length of the current stream in bytes.An indicating the length of the current stream in bytes.To be added.FILESTREAM Data in SQL Server 2008 (ADO.NET)
Gets or sets the position within the current stream.The current position within the .To be added.FILESTREAM Data in SQL Server 2008 (ADO.NET)
Gets or sets a value, in milliseconds, that determines how long the stream will attempt to read before timing out.A value, in milliseconds, that determines how long the stream will attempt to read before timing out.To be added.FILESTREAM Data in SQL Server 2008 (ADO.NET)
Gets or sets a value, in milliseconds, that determines how long the stream will attempt to write before timing out.A value, in milliseconds, that determines how long the stream will attempt to write before timing out.To be added.FILESTREAM Data in SQL Server 2008 (ADO.NET)
Clears all buffers for this stream and causes any buffered data to be written to the underlying device.To be added.FILESTREAM Data in SQL Server 2008 (ADO.NET)
The buffer to read the data into.The byte offset in at which to begin writing data read from the stream.The maximum number of bytes to read.An optional asynchronous callback, to be called when the read is complete.A user-provided object that distinguishes this particular asynchronous read request from other requestsBegins an asynchronous read operation.An that represents the asynchronous read, which could still be pending.
property to determine whether the current instance supports reading.
]]>
Reading data is not supported on the stream.FILESTREAM Data in SQL Server 2008 (ADO.NET)
The reference to the pending asynchronous request to finish.Waits for the pending asynchronous read to complete.The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams return zero (0) only at the end of the stream, otherwise, they should block until at least one byte is available.To be added.The object did not come from the corresponding method.FILESTREAM Data in SQL Server 2008 (ADO.NET)
The buffer to write data from.The byte offset in from which to begin writing.The maximum number of bytes to write.An optional asynchronous callback, to be called when the write is complete.A user-provided object that distinguishes this particular asynchronous write request from other requests.Begins an asynchronous write operation.An that represents the asynchronous write, which could still be pending.
property to determine whether the current instance supports writing.
]]>
Writing data is not supported on the stream.FILESTREAM Data in SQL Server 2008 (ADO.NET)
A reference to the outstanding asynchronous I/O request.Ends an asynchronous write operation.To be added.The object did not come from the corresponding method.FILESTREAM Data in SQL Server 2008 (ADO.NET)
A byte offset relative to the parameterA value of type indicating the reference point used to obtain the new positionSets the position within the current stream.The new position within the current stream.To be added.FILESTREAM Data in SQL Server 2008 (ADO.NET)
The desired length of the current stream in bytes.Sets the length of the current stream.
property to determine whether the current instance supports reading.
]]>
The object does not support reading of data.FILESTREAM Data in SQL Server 2008 (ADO.NET)
An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.The zero-based byte offset in buffer at which to begin storing the data read from the current stream.The maximum number of bytes to be read from the current stream.Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
property to determine whether the current instance supports writing.
]]>
The object does not support reading of data.FILESTREAM Data in SQL Server 2008 (ADO.NET)
Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.The unsigned byte cast to an , or -1 if at the end of the stream.
property to determine whether the current instance supports reading.
]]>
The object does not support reading of data.FILESTREAM Data in SQL Server 2008 (ADO.NET)
An array of bytes. This method copies bytes from to the current stream.The zero-based byte offset in at which to begin copying bytes to the current stream.The number of bytes to be written to the current stream.Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
property to determine whether the current instance supports writing.
]]>
The object does not support writing of data.FILESTREAM Data in SQL Server 2008 (ADO.NET)
The byte to write to the stream.Writes a byte to the current position in the stream and advances the position within the stream by one byte.
property to determine whether the current instance supports writing.
]]>
The object does not support writing of data.FILESTREAM Data in SQL Server 2008 (ADO.NET)
This class implements and is used for active directory federated authentication mechanisms.
This class implements and is used for active directory federated authentication mechanisms.
Initializes the class.
Client Application Id to be used for acquiring an access token for federated authentication. The driver uses its own application client id by default.
Initializes the class with the provided application client id.
Clears cached user tokens from the token provider.This will cause interactive authentication prompts to appear again if tokens were previously being obtained from the cache.
The callback method to be used with 'Active Directory Device Code Flow' authentication.(Optional) Client Application Id to be used for acquiring an access token for federated authentication. The driver uses its own application client id by default.
Initializes the class with the provided device code flow callback method and application client id.
The Active Directory authentication parameters passed to authentication providers.Acquires a security token from the authority.Represents an asynchronous operation that returns the authentication token.
The callback method to be used with 'Active Directory Device Code Flow' authentication.Sets the callback method, overriding the default implementation that processes the result for 'Active Directory Device Code Flow' authentication.
The callback method to be called by MSAL.NET to delegate the Web user interface with the Secure Token Service (STS).Sets a callback method which is invoked with a custom Web UI instance that will let the user sign-in with Azure Active Directory, present consent if needed, and get back the authorization code. Applicable when working with Active Directory Interactive authentication.The "authorizationUri" is crafted to leverage PKCE in order to protect the token from a man in the middle attack. Only MSAL.NET can redeem the code. In the event of cancellation, the implementer should return .
The authentication method.Indicates whether the specified authentication method is supported.
if the specified authentication method is supported; otherwise, .
are:
- Active Directory Password
- Active Directory Integrated
- Active Directory Interactive
- Active Directory Service Principal
- Active Directory Device Code Flow
- Active Directory Managed Identity
- Active Directory MSI
- Active Directory Default
]]>
The authentication method.This method is called immediately before the provider is added to authentication provider registry. Avoid performing long-waiting tasks in this method, since it can block other threads from accessing the provider registry.
The authentication method.This method is called immediately before the provider is removed from the authentication provider registry. For example, this method is called when a different provider with the same authentication method overrides this provider in the authentication provider registry. Avoid performing long-waiting task in this method, since it can block other threads from accessing the provider registry.
The parent as an object, in order to be used from shared .NET Standard assemblies.Sets a reference to the ViewController (if using Xamarin.iOS), Activity (if using Xamarin.Android) IWin32Window or IntPtr (if using .NET Framework). Used for invoking the browser for Active Directory Interactive authentication.Mandatory to be set only on Android. See https://aka.ms/msal-net-android-activity for further documentation and details.
Specifies a value for . Possible values are and .
To be added.
The application workload type when connecting to a server is read only.11
The application workload type when connecting to a server is read write.00
Specifies a value for the property. To be added.
Blocking period OFF for Azure SQL servers, but ON for all other SQL servers.0
Blocking period ON for all SQL servers including Azure SQL servers.1
Blocking period OFF for Azure SQL servers, but ON for all other SQL servers.2
The source of the event.
A object that contains the event data.
Handles the event that is fired when a notification is received for any of the commands associated with a object.
event does not necessarily imply a change in the data. Other circumstances, such as time-out expired and failure to set the notification request, also generate .
]]>
Specifies how rows of data are sorted.
To be added.
The default. No sort order is specified.-1-1
Rows are sorted in ascending order.00
Rows are sorted in descending order.11
Called from constructors in derived classes to initialize the class.To be added.
Default Constructor to initialize the class.
When overridden in a derived class, initializes the authentication initializer. This method is called by the constructor during startup.
Describes the different SQL authentication methods that can be used by a client connecting to Azure SQL Database. For details, see Connecting to SQL Database By Using Azure Active Directory Authentication.
To be added.
The authentication method is not specified.0
The authentication method is Sql Password.1
The authentication method uses Active Directory Password. Use Active Directory Password to connect to a SQL Database using an Azure AD principal name and password.2
The authentication method uses Active Directory Integrated. Use Active Directory Integrated to connect to a SQL Database using integrated Windows authentication.3
The authentication method uses Active Directory Interactive. Use Active Directory Interactive to connect to a SQL Database with an interactive authentication flow.4
The authentication method uses Active Directory Service Principal. Use Active Directory Service Principal to connect to a SQL Database using the client ID and secret of a service principal identity.5
The authentication method uses Active Directory Device Code Flow. Use Active Directory Device Code Flow to connect to a SQL Database from devices and operating systems that do not provide a Web browser, using another device to perform interactive authentication.6
The authentication method uses Active Directory Managed Identity. Use System Assigned or User Assigned Managed Identity to connect to SQL Database from Azure client environments that have enabled support for Managed Identity. For User Assigned Managed Identity, 'User Id' or 'UID' is required to be set to the "client ID" of the user identity.7
Alias for "Active Directory Managed Identity" authentication method. Use System Assigned or User Assigned Managed Identity to connect to SQL Database from Azure client environments that have enabled support for Managed Identity. For User Assigned Managed Identity, 'User Id' or 'UID' is required to be set to the "client ID" of the user identity.8
The authentication method uses Active Directory Default. Use this mode to connect to a SQL Database using multiple non-interactive authentication methods tried sequentially to acquire an access token. This method does not fallback to the "Active Directory Interactive" authentication method.9
The authentication method uses Active Directory Workload Identity. Use a federated User Assigned Managed Identity to connect to SQL Database from Azure client environments that have enabled support for Workload Identity. The 'User Id' or 'UID' is required to be set to the "client ID" of the user identity.10
Represents AD authentication parameters passed by a driver to authentication providers.
One of the enumeration values that specifies the authentication method.The server name.The database name.The resource URI.The authority URI.The user login name/ID.The user password.The connection ID.The connection timeout value in seconds.Initializes a new instance of the class using the specified authentication method, server name, database name, resource URI, authority URI, user login name/ID, user password, connection ID and connection timeout value.
Gets the authentication method.The authentication method.
Gets the authority URI.The authority URI.
Gets the connection ID.The connection ID.
Gets the database name.The database name.
Gets the user password.The user password.
The resource URIs.The resource URI.
Gets the server name.The server name.
Gets the user login name/ID.The user login name/ID.
Gets the connection timeout value.The connection timeout value to be passed to Cancellation Token Source.
Defines the core behavior of authentication providers and provides a base class for derived classes.
Called from constructors in derived classes to initialize the class.
The Active Directory authentication parameters passed by the driver to authentication providers.Acquires a security token from the authority.Represents an asynchronous operation that returns the AD authentication token.To be added.
The authentication method.This method is called immediately before the provider is added to SQL drivers registry. Avoid performing long-waiting tasks in this method, since it can block other threads from accessing the provider registry.
The authentication method.This method is called immediately before the provider is removed from the SQL drivers registry. For example, this method is called when a different provider with the same authentication method overrides this provider in the SQL drivers registry. Avoid performing long-waiting task in this method, since it can block other threads from accessing the provider registry.
The authentication method.Gets an authentication provider by method.
The authentication provider or if not found.
To be added.
The authentication method.Indicates whether the specified authentication method is supported.
if the specified authentication method is supported; otherwise, .
To be added.
The authentication method.The authentication provider.Sets an authentication provider by method.
if the operation succeeded; otherwise, (for example, the existing provider disallows overriding).
To be added.
Represents an AD authentication token.
The access token.The token expiration time.Initializes a new instance of the class.The parameter is or empty.
Gets the token string.The token string.
Gets the token expiration time.The token expiration time.
Lets you efficiently bulk load a SQL Server table with data from another source.
class lets you write managed code solutions that provide similar functionality. There are other ways to load data into a SQL Server table (INSERT statements, for example), but offers a significant performance advantage over them. The class can be used to write data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a instance or read with a instance. will fail when bulk loading a column of type into a SQL Server column whose type is one of the date/time types added in SQL Server 2008.
## Examples
The following console application demonstrates how to load data using the class.
In this example, a is used to copy data from the **Production.Product** table in the SQL Server **AdventureWorks** database to a similar table in the same database.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance,
it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[BulkCopy.Single#1](~/../sqlclient/doc/samples/SqlBulkCopy_Single.cs#1)]
]]>
The already open
instance that will be used to perform the bulk copy operation. If your connection string does not use
, you can use
to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string.
Initializes a new instance of the
class using the specified open instance of
.
instance is initialized, the connection remains open after the instance is closed.
If the `connection` argument is null, an is thrown.
## Examples
The following console application demonstrates how to bulk load data using a connection that is already open. In this example, a
is used to copy data from the **Production.Product** table in the SQL Server **AdventureWorks** database to a similar table in the same database. This example is for demonstration
purposes only. You would not use `SqlBulkCopy` to move data from one table to another in the same database in a production application.
Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a
.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[BulkCopy.Single#1](~/../sqlclient/doc/samples/SqlBulkCopy_Single.cs#1)]
]]>
The already open
instance that will be used to perform the bulk copy. If your connection string does not use
, you can use
to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string.
A combination of values from the
enumeration that determines which data source rows are copied to the destination table.
An existing
instance under which the bulk copy will occur.
Initializes a new instance of the
class using the supplied existing open instance of
. The
instance behaves according to options supplied in the
parameter. If a non-null
is supplied, the copy operations will be performed within that transaction.
Performing Bulk Copy Operations
Overview of the SqlClient driver
The string defining the connection that will be opened for use by the
instance.
If your connection string does not use
, you can use
or
and
to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string.
Initializes and opens a new instance of
based on the supplied
. The constructor uses the
to initialize a new instance of the
class.
is thrown. If `connectionString` is an empty string, an is thrown.
## Examples
The following console application demonstrates how to bulk load data by using a connection specified as a string. The connection is automatically
closed when the instance is closed.
In this example, the source data is first read from a SQL Server table to a instance.
The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a .
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance,
it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ConnectionString#1](~/../sqlclient/doc/samples/SqlBulkCopy_ConnectionString.cs#1)]
]]>
If `connectionString` is an empty string, an
is thrown.
The string defining the connection that will be opened for use by the
instance. If your connection string does not use
, you can use
or
and
to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string.
A combination of values from the
enumeration that determines which data source rows are copied to the destination table.
Initializes and opens a new instance of
based on the supplied
. The constructor uses that
to initialize a new instance of the
class. The
instance behaves according to options supplied in the
parameter.
topic.
## Examples
The following console application demonstrates how to perform a bulk load by using a connection specified as a string.
An option is set to use the value in the identity column of the source table when you load the destination table. In this example,
the source data is first read from a SQL Server table to a instance.
The source table and destination table each include an Identity column. By default, a new value for the **Identity** column is generated in the destination table for each row added.
In this example, an option is set when the connection is opened that forces the bulk load process to use the **Identity** values from the source table instead.
To see how the option changes the way the bulk load works, run the sample with the **dbo.BulkCopyDemoMatchingColumns** table empty. All rows load from the source.
Then run the sample again without emptying the table. An exception is thrown and the code writes a message to the console notifying you that rows weren't
added because of primary key constraint violations.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided to
demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement
to copy the data.
[!code-csharp[SqlBulkCopy.KeepIdentity#1](~/../sqlclient/doc/samples/SqlBulkCopy_KeepIdentity.cs#1)]
]]>
Number of rows in each batch. At the end of each batch, the rows in the batch are sent to the server.
The integer value of the
property, or zero if no value has been set.
rows have been processed or there are no more rows to send to the destination data source.
Zero (the default) indicates that each operation is a single batch.
If the instance has been declared without the option in effect,
rows are sent to the server rows at a time, but no transaction-related action is taken.
If is in effect, each batch of rows is inserted as a separate transaction.
The property can be set at any time. If a bulk copy is already in progress, the current batch is sized according to the previous batch size.
Subsequent batches use the new size. If the is initially zero and changed while a
operation is already in progress, that operation loads the data as a single batch. Any subsequent
operations on the same instance use the new .
## Examples
The following console application demonstrates how to bulk load data in batches of 50 rows. For an example illustrating how
works with a transaction, see [Transaction and Bulk Copy Operations](/sql/connect/ado-net/sql/transaction-bulk-copy-operations).
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance,
it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.BatchSize#1](~/../sqlclient/doc/samples/SqlBulkCopy_BatchSize.cs#1)]
]]>
Number of seconds for the operation to complete before it times out.
The integer value of the
property. The default is 30 seconds. A value of 0 indicates no limit; the bulk copy will wait indefinitely.
instance.
The source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a .
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.Timeout#1](~/../sqlclient/doc/samples/SqlBulkCopy_Timeout.cs#1)]
]]>
Enables or disables a
object to stream data from an
object
if a
object can stream data from an
object; otherwise, false. The default is
.
is `true`, reads from an object using ,
optimizing memory usage by using the streaming capabilities. Streaming is only applicable to max data types (i.e.
VARBINARY(MAX), VARCHAR(MAX), NVARCHAR(MAX), and XML). When is set to false,
the class loads all the data returned by the object into memory before sending it to the server.
> [!NOTE]
> The main advantage of enabling streaming is reducing memory usage during bulk copy of max data types.
]]>
Returns a collection of
items. Column mappings define the relationships between columns in the data source and columns in the destination.
A collection of column mappings. By default, it is an empty collection.
collection is unnecessary. However, if the column counts differ,
or the ordinal positions are not consistent, you must use to make sure that data is copied into the correct columns.
During the execution of a bulk copy operation, this collection can be accessed, but it cannot be changed. Any attempt to change it will throw an .
]]>
Returns a collection of
items. Column order hints describe the sort order of columns in the clustered index of the destination table.
A collection of column order hints. By default, it is an empty collection.
Name of the destination table on the server.
The string value of the
property, or null if none as been supplied.
has not been set when is called, an
is thrown. If is modified while a operation is running,
the change does not affect the current operation. The new value is used the next time a method is called.
is a three-part name (`..`). You can qualify the table name with its database and owning schema if you choose.
However, if the table name uses an underscore ("_") or any other special characters, you must escape the name using surrounding brackets as in (`[..]`).
You can bulk-copy data to a temporary table by using a value such as `tempdb..#table` or `tempdb..#table` for the property.
## Examples
The following console application demonstrates how to bulk load data using a connection that is already open. The destination table is a table in the **AdventureWorks** database.
In this example, the connection is first used to read data from a SQL Server table to a instance. The source data does not have to
be located on SQL Server; you can use any data source that can be read to an or loaded to a .
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance,
it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.Single#1](~/../sqlclient/doc/samples/SqlBulkCopy_Single.cs#1)]
]]>
Defines the number of rows to be processed before generating a notification event.
The integer value of the
property, or zero if the property has not been set.
property can be set at any time, even while a bulk copy operation is underway. Changes made during a bulk copy operation take effect after
the next notification. The new setting applies to all subsequent operations on the same instance.
If is set to a number less than zero, an is thrown.
## Examples
The following console application demonstrates how to bulk load data using a connection that is already open. The property is set so that
the event handler is called after every 50 rows copied to the table.
In this example, the connection is first used to read data from a SQL Server table to a instance. Then a second connection is opened to bulk copy the data.
Note that the source data does not have to be located on SQL Server; you can use any data source that can be read to an or loaded to a .
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided to
demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT`
statement to copy the data.
[!code-csharp[SqlBulkCopy.NotifyAfter#1](~/../sqlclient/doc/samples/SqlBulkCopy_NotifyAfter.cs#1)]
]]>
The number of rows processed in the ongoing bulk copy operation.
The integer value of the
property.
event and does not imply that this number of rows has been sent to the server or committed.
This value can be accessed during or after the execution of a bulk copy operation.
This value will wrap around and become negative if the number of rows exceeds int.MaxValue. Consider using the property.
]]>
The number of rows processed in the ongoing bulk copy operation.
The long value of the property.
event and does not imply that this number of rows has been sent to the server or committed.
This value can be accessed during or after the execution of a bulk copy operation.
]]>
Occurs every time that the number of rows specified by the
property have been processed.
and are independent. Receipt of a
event does not imply that any rows have been sent to the server or committed.
You cannot call SqlBulkCopy.Close () or SqlConnection.Close () from this event.
Doing this will cause an being thrown, and the object state will not change. If the user wants to cancel the
operation from the event, the property of the can be used.
(See [Transaction and Bulk Copy Operations](/sql/connect/ado-net/sql/transaction-bulk-copy-operations) for examples that use the
property.)
No action, such as transaction activity, is supported in the connection during the execution of the bulk copy operation, and it is recommended that you not use the same connection used
during the event. However, you can open a different connection.
## Examples
The following console application demonstrates how to bulk load data using a connection that is already open. The property is set so that
the event handler is called after every 50 rows copied to the table.
In this example, the connection is first used to read data from a SQL Server table to a instance. Note that the source data does not have to be located on
SQL Server; you can use any data source that can be read to an or loaded to a .
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier
and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.NotifyAfter#1](~/../sqlclient/doc/samples/SqlBulkCopy_NotifyAfter.cs#1)]
]]>
Closes the instance.
on the object, no other operation will succeed. Calls to the method will throw an . Calling the method from the event causes an to be thrown.
Note that open instances are closed implicitly at the end of a `using` block.
## Examples
The following example uses the same instance to add sales orders and their associated details to two destination tables. Because the **AdventureWorks** sales order tables are large, the sample reads only orders placed by a certain account number and bulk copies those orders and details to the destination tables. The method is used only after both bulk copy operations are complete.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.OrdersDetails#1](~/../sqlclient/doc/samples/SqlBulkCopy_OrdersDetails.cs#1)]
]]>
Releases all resources used by the current instance of the
class.
. The `Dispose` method leaves the in an unusable state.
After calling `Dispose`, you must release all references to the so the garbage collector can reclaim the memory that the
was occupying.
For more information, see [Cleaning Up Unmanaged Resources](/dotnet/standard/garbage-collection/unmanaged) and
[Implementing a Dispose Method](/dotnet/standard/garbage-collection/implementing-dispose).
> [!NOTE]
> Always call `Dispose` before you release your last reference to the . Otherwise, the resources it is using will not be freed until the garbage collector calls
the object's `Finalize` method.
]]>
A
whose rows will be copied to the destination table.
Copies all rows from the supplied
array to a destination table specified by the
property of the
object.
To be added.
A
did not specify a valid destination column name.
A
whose rows will be copied to the destination table.
Copies all rows in the supplied
to a destination table specified by the
property of the
object.
are copied to the destination table except those that have been deleted.
While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection.
The collection maps from the columns to the destination database table.
## Examples
The following Console application demonstrates how to bulk load data from a . The destination table is a table in the **AdventureWorks** database.
In this example, a is created at run time and is the source of the `SqlBulkCopy` operation.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.DataTable#1](~/../sqlclient/doc/samples/SqlBulkCopy_DataTable.cs#1)]
]]>
A
did not specify a valid destination column name.
Performing Bulk Copy Operations
Overview of the SqlClient driver
A
whose rows will be copied to the destination table.
A value from the
enumeration. Only rows matching the row state are copied to the destination.
Copies only rows that match the supplied row state in the supplied
to a destination table specified by the
property of the
object.
that are in the states indicated in the `rowState` argument and have not been deleted are copied to the destination table.
> [!NOTE]
> If is specified, any , , and
rows will also be copied to the server. No exception will be raised.
While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection.
The collection maps from the columns to the destination database table.
## Examples
The following Console application demonstrates how to bulk load only the rows in a that match a specified state. In this case, only unchanged rows are added. The destination table is a table in the **AdventureWorks** database.
In this example, a is created at run time and three rows are added to it. Before the method is executed, one of the rows is edited.
The method is called with a `DataRowState.Unchanged` `rowState` argument, so only the two unchanged rows are bulk copied to the destination.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.DataRowState#1](~/../sqlclient/doc/samples/SqlBulkCopy_DataRowState.cs#1)]
]]>
A
did not specify a valid destination column name.
An array of objects that will be copied to the destination table.Copies all rows from the supplied array to a destination table specified by the property of the object.
is busy serving it, and no other operations can be performed on the connection.
The collection maps from the columns to the destination database table.
## Examples
The following console application demonstrates how to bulk load data from a array. The destination table is a table in the **AdventureWorks** database.
In this example, a is created at run time. A single row is selected from the to copy to the destination table.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.RowArray#1](~/../sqlclient/doc/samples/SqlBulkCopy_RowArray.cs#1)]
]]>
A
did not specify a valid destination column name.
A
whose rows will be copied to the destination table.
Copies all rows in the supplied
to a destination table specified by the
property of the
object.
or a similar call,
so the next available row is the first row. To process multiple results, call on the data reader and call
again.
Note that using modifies the state of the reader. The method will call
until it returns false, the operation is aborted, or an error occurs. This means that the data reader will be in a different state, probably at the end of the result set,
when the operation is complete.
While the bulk copy operation is in progress, the associated destination is busy serving it, and no other operations can be performed on the connection.
The collection maps from the data reader columns to the destination database table.
## Examples
The following console application demonstrates how to bulk load data from a . The destination table is a table in the **AdventureWorks** database.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is provided
to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ConnectionString#1](~/../sqlclient/doc/samples/SqlBulkCopy_ConnectionString.cs#1)]
]]>
A
did not specify a valid destination column name.
A
whose rows will be copied to the destination table.
The asynchronous version of
,
which copies all rows in the supplied
to a destination table specified by the
property of the
object.
A task representing the asynchronous operation.
Calling
multiple times for the same instance before task completion.
Calling
and
for the same instance before task completion.
The connection drops or is closed during
execution.
Returned in the task object, the
object was closed during the method execution.
Returned in the task object, there was a connection pool timeout.
Returned in the task object, the
object is closed before method execution.
The
was closed before the completed
returned.
The
's associated connection was closed before the completed
returned.
A
did not specify a valid destination column name.
Returned in the task object, any error returned by SQL Server that occurred while opening the connection.
A
whose rows will be copied to the destination table.
The cancellation instruction. A
value in this parameter makes this method equivalent to
.
The asynchronous version of
,
which copies all rows from the supplied
array to a destination table specified by the
property of the
object.
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
To be added.
An array of
objects that will be copied to the destination table.
The asynchronous version of
,
which copies all rows from the supplied
array to a destination table specified by the
property of the
object.
A task representing the asynchronous operation.
Calling
multiple times for the same instance before task completion. Calling
and
for the same instance before task completion.
The connection drops or is closed during
execution.
Returned in the task object, the
object was closed during the method execution.
Returned in the task object, there was a connection pool timeout.
Returned in the task object, the
object is closed before method execution.
A
did not specify a valid destination column name.
Returned in the task object, any error returned by SQL Server that occurred while opening the connection.
An array of
objects that will be copied to the destination table.
The cancellation instruction. A
value in this parameter makes this method equivalent to
.
The asynchronous version of
,
which copies all rows from the supplied
array to a destination table specified by the
property of the
object.
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
Calling
multiple times for the same instance before task completion.
Calling
and
for the same instance before task completion.
The connection drops or is closed during
execution.
Returned in the task object, the
object was closed during the method execution.
Returned in the task object, there was a connection pool timeout.
Returned in the task object, the
object is closed before method execution.
A
did not specify a valid destination column name.
Returned in the task object, any error returned by SQL Server that occurred while opening the connection.
A
whose rows will be copied to the destination table.
The asynchronous version of
,
which copies all rows in the supplied
to a destination table specified by the
property of the
object.
A task representing the asynchronous operation.
Calling
multiple times for the same instance before task completion.
Calling
and
for the same instance before task completion.
The connection drops or is closed during
execution.
Returned in the task object, the
object was closed during the method execution.
Returned in the task object, there was a connection pool timeout.
Returned in the task object, the
object is closed before method execution.
A
did not specify a valid destination column name.
Returned in the task object, any error returned by SQL Server that occurred while opening the connection.
A
whose rows will be copied to the destination table.
A value from the
enumeration. Only rows matching the row state are copied to the destination.
The asynchronous version of
,
which copies only rows that match the supplied row state in the supplied
to a destination table specified by the
property of the object.
A task representing the asynchronous operation.
Calling
multiple times for the same instance before task completion.
Calling
and
for the same instance before task completion.
The connection drops or is closed during
execution.
Returned in the task object, the
object was closed during the method execution.
Returned in the task object, there was a connection pool timeout.
Returned in the task object, the
object is closed before method execution.
A
did not specify a valid destination column name.
Returned in the task object, any error returned by SQL Server that occurred while opening the connection.
A
whose rows will be copied to the destination table.
A value from the
enumeration. Only rows matching the row state are copied to the destination.
The cancellation instruction. A
value in this parameter makes this method equivalent to
.
The asynchronous version of
,
which copies only rows that match the supplied row state in the supplied
to a destination table specified by the
property of the
object.
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
Calling
multiple times for the same instance before task completion.
Calling
and
for the same instance before task completion.
The connection drops or is closed during
execution.
Returned in the task object, the
object was closed during the method execution.
Returned in the task object, there was a connection pool timeout.
Returned in the task object, the
object is closed before method execution.
A
did not specify a valid destination column name.
Returned in the task object, any error returned by SQL Server that occurred while opening the connection.
A
whose rows will be copied to the destination table.
The cancellation instruction. A
value in this parameter makes this method equivalent to
.
The asynchronous version of
,
which copies all rows in the supplied
to a destination table specified by the
property of the
object.
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
Calling
multiple times for the same instance before task completion.
Calling
and
for the same instance before task completion.
The connection drops or is closed during
execution.
Returned in the task object, the
object was closed during the method execution.
Returned in the task object, there was a connection pool timeout.
Returned in the task object, the
object is closed before method execution.
A
did not specify a valid destination column name.
Returned in the task object, any error returned by SQL Server that occurred while opening the connection.
A
whose rows will be copied to the destination table.
The asynchronous version of
,
which copies all rows in the supplied
to a destination table specified by the
property of the
object.
A task representing the asynchronous operation.
Calling
multiple times for the same
instance before task completion.
Calling
and
for the same instance before task completion.
The connection drops or is closed during
execution.
Returned in the task object, the
object was closed during the method execution.
Returned in the task object, there was a connection pool timeout.
Returned in the task object, the
object is closed before method execution.
The
was closed before the completed
returned.
The
's associated connection was closed before the completed
returned.
A
did not specify a valid destination column name.
Returned in the task object, any error returned by SQL Server that occurred while opening the connection.
A
whose rows will be copied to the destination table.
The cancellation instruction. A
value in this parameter makes this method equivalent to
.
The asynchronous version of
,
which copies all rows in the supplied
to a destination table specified by the
property of the
object.
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
Calling
multiple times for the same instance before task completion.
Calling
and
for the same instance before task completion.
The connection drops or is closed during
execution.
Returned in the task object, the
object was closed during the method execution.
Returned in the task object, there was a connection pool timeout.
Returned in the task object, the
object is closed before method execution.
The
was closed before the completed
returned.
The
's associated connection was closed before the completed
returned.
A
did not specify a valid destination column name.
Returned in the task object, any error returned by SQL Server that occurred while opening the connection.
Defines the mapping between a column in a
instance's data source and a column in the instance's destination table.
collection is empty - the columns are mapped implicitly based on ordinal position.
For this to work, source and target schemas must match. If they do not, an will be thrown.
If the collection is not empty, not every column present in the data source has to be specified. Those not mapped by the collection
are ignored.
You can refer to source and target columns by either name or ordinal. You can also mix by-name and by-ordinal column references in the same mappings collection.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. Although the number of columns in the
destination matches the number of columns in the source, and each destination column is in the same ordinal position as its corresponding source column, the column names do not match.
objects are used to create a column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMapping#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMapping.cs#1)]
]]>
Parameterless constructor that initializes a new
object.
property or the property, and define the destination for the mapping using the
property or the property.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database.
Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match.
objects are used to create a column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance,
it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMapping#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMapping.cs#1)]
]]>
The ordinal position of the source column within the data source.
The ordinal position of the destination column within the destination table.
Creates a new column mapping, using column ordinals to refer to source and destination columns.
objects are used to create a column map for the bulk copy based on the ordinal positions of the columns.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier
and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingOrdinal#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingOrdinal.cs#1)]
]]>
The ordinal position of the source column within the data source.
The name of the destination column within the destination table.
Creates a new column mapping, using a column ordinal to refer to the source column and a column name for the target column.
objects are used to create a
column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and
faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingOrdinalName#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingOrdinalName.cs#1)]
]]>
The name of the source column within the data source.
The ordinal position of the destination column within the destination table.
Creates a new column mapping, using a column name to refer to the source column and a column ordinal for the target column.
objects are used to create
a column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup). This code is
provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to
use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingNameOrdinal#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingNameOrdinal.cs#1)]
]]>
The name of the source column within the data source.
The name of the destination column within the destination table.
Creates a new column mapping, using column names to refer to source and destination columns.
objects are used to create a
column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMapping#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMapping.cs#1)]
]]>
Name of the column being mapped in the destination database table.
The string value of the
property.
and properties are mutually exclusive.
The last value set takes precedence.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database.
Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match.
objects are used to create a column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingDestinationColumn#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs#1)]
]]>
Ordinal value of the destination column within the destination table.
The integer value of the
property, or -1 if the property has not been set.
and properties are mutually exclusive.
The last value set takes precedence.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. Although the number of columns in the
destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a
column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingDestinationOrdinal#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs#1)]
]]>
Name of the column being mapped in the data source.
The string value of the
property.
and properties are mutually exclusive.
The last value set takes precedence.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. Although the number of columns in the
destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a
column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingDestinationColumn#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingDestinationColumn.cs#1)]
]]>
The ordinal position of the source column within the data source.
The integer value of the
property.
and properties are mutually exclusive.
The last value set takes precedence.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. Although the number of columns in the destination
matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a column map for the
bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingDestinationOrdinal#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingDestinationOrdinal.cs#1)]
]]>
Collection of objects that inherits from .
collection is empty - the columns are mapped implicitly based on ordinal position.
For this to work, source and target schemas must match. If they do not, an is thrown.
If the collection is not empty, not every column present in the data source has to be specified. Those not mapped by the collection are
ignored.
You can refer to source and target columns by either name or ordinal. You can mix by-name and by-ordinal column references in the same mappings collection.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database.
Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match.
are added to the for the
object to create a column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to
use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingCollection#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingCollection.cs#1)]
]]>
The zero-based index of the to find.Gets the object at the specified index.A object.To be added.
The object that describes the mapping to be added to the collection.Adds the specified mapping to the .A object.
objects are used to create a column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance,
it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMapping#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMapping.cs)]
]]>
The ordinal position of the source column within the data source.The ordinal position of the destination column within the destination table.Creates a new and adds it to the collection, using ordinals to specify both source and destination columns.A column mapping.
is thrown.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database.
Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match.
objects are used to create a column map for the bulk copy using the ordinal position of the source and destination columns.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingCollectionOrdinal#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingCollectionOrdinal.cs#1)]
]]>
The ordinal position of the source column within the data source.The name of the destination column within the destination table.Creates a new and adds it to the collection, using an ordinal for the source column and a string for the destination column.A column mapping.
is thrown.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database. Although the number of columns in the
destination matches the number of columns in the source, the column names and ordinal positions do not match. objects are used to create a
column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy_ColumnMappingIndexColName#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingIndexColName.cs#1)]
]]>
The name of the source column within the data source.The ordinal position of the destination column within the destination table.Creates a new and adds it to the collection, using a column name to describe the source column and an ordinal to specify the destination column.A column mapping.
is thrown.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database.
Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match.
objects are used to create a column map for the bulk copy.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance,
it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingColNameIndex#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingColNameIndex.cs#1)]
]]>
The name of the source column within the data source.The name of the destination column within the destination table.Creates a new and adds it to the collection, using column names to specify both source and destination columns.A column mapping.
is thrown.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database.
Although the number of columns in the destination matches the number of columns in the source, the column names and ordinal positions do not match. The code creates a
object by specifying the column names.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance,
it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingCollection#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingCollection.cs#1)]
]]>
Clears the contents of the collection.
method is most commonly used when you use a single
instance to process more than one bulk copy operation. If you create column mappings for one bulk copy operation, you must clear the
after the method and before processing the next bulk copy.
Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate
for each operation.
## Examples
The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details.
Although not strictly necessary in this example (because the ordinal positions of the source and destination columns do match), the example defines column mappings for each bulk copy operation.
The method must be used after the first bulk copy is performed and before the next bulk copy's column mappings are defined.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingOrdersDetails#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingOrdersDetails.cs#1)]
]]>
A valid object.Gets a value indicating whether a specified object exists in the collection.
if the specified mapping exists in the collection; otherwise .
The one-dimensional array that is the destination of the elements copied from
. The array must have zero-based indexing.The zero-based index in at which copying begins.Copies the elements of the to an array of
items, starting at a particular index.
The object for which to search.Gets the index of the specified object.The zero-based index of the column mapping, or -1 if the column mapping is not found in the collection.To be added.
Integer value of the location within the at which to insert the new
.
object to be inserted in the collection.Insert a new at the index specified.To be added.
object to be removed from the collection.Removes the specified element from the .
method is most commonly used when you use a single
instance to process more than one bulk copy operation. If you create column mappings for one bulk copy operation, you must remove mappings that no longer apply after the
method is called and before defining mapping for the next bulk copy. You can clear the entire collection by using the
method, or remove mappings individually using the
method or the method.
Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate
for each operation.
## Examples
The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details.
Although not strictly necessary in this example (because the ordinal positions of the source and destination columns do match), the example defines column mappings for each bulk copy operation.
Both bulk copies include a mapping for the **SalesOrderID**, so rather than clearing the entire collection between bulk copy operations, the example removes all mappings except for the **SalesOrderID**
mapping and then adds the appropriate mappings for the second bulk copy operation.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingRemove#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingRemove.cs#1)]
]]>
The zero-based index of the object to be removed from the collection.Removes the mapping at the specified index from the collection.
method is most commonly used when you use a single
instance to process more than one bulk copy operation. If you create column mappings for one bulk copy operation, you must remove mappings that no longer apply after the
method is called and before defining mapping for the next bulk copy. You can clear the entire collection by using the
method, or remove mappings individually using the
method or the method.
Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate
for each operation.
## Examples
The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details.
Although not strictly necessary in this example (because the ordinal positions of the source and destination columns do match), the example defines column mappings for each bulk copy operation.
Both bulk copies include a mapping for the **SalesOrderID**, so rather than clearing the entire collection between bulk copy operations, the example removes all mappings except for the
**SalesOrderID** mapping and then adds the appropriate mappings for the second bulk copy operation.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnMappingRemoveAt#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnMappingRemoveAt.cs#1)]
]]>
Defines the sort order for a column in a
instance's destination table, according to the clustered index on the table.
collection is not empty, order hints can only be provided for valid
destination columns which have been mapped.
If a of Unspecified is given, an will be thrown.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database.
A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnOrderHint#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHint.cs#1)]
]]>
The name of the destination column within the destination table.
The sort order of the corresponding destination column.
Creates a new column order hint for the specified destination column.
[!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnOrderHint#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHint.cs#1)]
]]>
Name of the destination column in the destination table for which the hint is being provided.
The string value of the
property.
will be thrown if a null or empty string is given.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database.
A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnOrderHintColumn#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintColumn.cs#1)]
]]>
The value is null or empty.
The sort order of the destination column in the destination table.
The SortOrder value of the
property.
will be thrown if a of Unspecified is given.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database.
A SqlBulkCopyColumnOrderHint object is used to define the sort order for the ProductNumber destination column.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnOrderHintSortOrder#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintSortOrder.cs#1)]
]]>
The sort order cannot be unspecified for a column order hint.
Collection of objects that inherits from .
collection is not empty, order hints can only be provided for valid
destination columns which have been mapped.
If a of Unspecified is given, an will be thrown.
## Examples
The following example bulk copies data from a source table in the **AdventureWorks** sample database to a destination table in the same database.
s are added to the of the
object to specify order hints for the bulk copy operation.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to
use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnOrderHintCollection#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollection.cs#1)]
]]>
The zero-based index of the to find.Gets the object at the specified index.A object.To be added.The index must be non-negative and less than the size of the collection.
The object that describes the order hint to be added to the collection.Adds the specified order hint to the .A object.
[!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance,
it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnOrderHintCollectionAdd#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd.cs)]
]]>
The value is null.
The name of the destination column within the destination table.The sort order of the corresponding destination column.Creates a new and adds it to the collection.A column column order hint.
by providing the destination column name and its sort order.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnOrderHintCollectionAdd2#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionAdd2.cs#1)]
]]>
Clears the contents of the collection.
method is most commonly used when you use a single
instance to process more than one bulk copy operation. If you create column order hints for one bulk copy operation, you must clear the
after the method and before processing the next bulk copy.
Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate
for each operation.
## Examples
The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details.
The example defines a column order hint for each bulk copy operation.
The method must be used after the first bulk copy is performed and before the next bulk copy's order hint is defined.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnOrderHintCollectionClear#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionClear.cs#1)]
]]>
A valid object.Gets a value indicating whether a specified object exists in the collection.
if the specified column order hint exists in the collection; otherwise .
The one-dimensional array that is the destination of the elements copied from
. The array must have zero-based indexing.The zero-based index in at which copying begins.Copies the elements of the to an array of
items, starting at a particular index.
The object for which to search.Gets the index of the specified object.The zero-based index of the column order hint, or -1 if the column order hint is not found in the collection.To be added.
Integer value of the location within the at which to insert the new
.
object to be inserted in the collection.Insert a new at the index specified.The order in which column order hints can be added is arbitrary.The index is less than zero or greater than the size of the collection.A null column order hint cannot be added to the collection.
object to be removed from the collection.Removes the specified element from the .
instance to process more than one bulk copy operation. If you create column order hints for one bulk copy operation, you must clear the
after the method and before processing the next bulk copy.
You can clear the entire collection by using the
method, or remove hints individually using the Remove method or the method.
Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate
for each operation.
## Examples
The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details.
The example defines a column order hint for the **OrderDate** column in the first bulk copy operation. The hint is removed before the second bulk copy operation.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnOrderHintCollectionRemove#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemove.cs#1)]
]]>
The value is null.
The zero-based index of the object to be removed from the collection.Removes the column order hint at the specified index from the collection.
method is most commonly used when you use a single
instance to process more than one bulk copy operation. If you create column order hints for one bulk copy operation, you must clear the
after the method and before processing the next bulk copy.
You can clear the entire collection by using the
method, or remove hints individually using the
method or the method.
Performing several bulk copies using the same instance will usually be more efficient from a performance point of view than using a separate
for each operation.
## Examples
The following example performs two bulk copy operations. The first operation copies sales order header information, and the second copies sales order details.
The example defines a column order hint for the **OrderDate** column in the first bulk copy operation. The hint is removed before the second bulk copy operation.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance, it is easier and faster to use a
Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.ColumnOrderHintCollectionRemoveAt#1](~/../sqlclient/doc/samples/SqlBulkCopy_ColumnOrderHintCollectionRemoveAt.cs#1)]
]]>
The index must be non-negative and less than the size of the collection.
Bitwise flag that specifies one or more options to use with an instance of .
enumeration when you construct a instance to change how the
methods for that instance behave.
## Examples
The following console application demonstrates how to perform a bulk load that copies the value in the identity column of the source table to the corresponding column in the destination table,
instead of generating a new value for each row's identity column.
To see how the option changes the way the bulk load works, run the sample with the **dbo.BulkCopyDemoMatchingColumns** table empty. All rows load from the source.
Next, run the sample again without emptying the table. An exception is thrown, and the code writes a message to the console window notifying you that rows were not added because of
primary key violations.
> [!IMPORTANT]
> This sample will not run unless you have created the work tables as described in [Bulk Copy Example Setup](/sql/connect/ado-net/sql/bulk-copy-example-setup).
This code is provided to demonstrate the syntax for using **SqlBulkCopy** only. If the source and destination tables are in the same SQL Server instance,
it is easier and faster to use a Transact-SQL `INSERT … SELECT` statement to copy the data.
[!code-csharp[SqlBulkCopy.KeepIdentity#1](~/../sqlclient/doc/samples/SqlBulkCopy_KeepIdentity.cs)]
]]>
Check constraints while data is being inserted. By default, constraints are not checked.
Use the default values for all options.
When specified, cause the server to fire the insert triggers for the rows being inserted into the database.
Preserve source identity values. When not specified, identity values are assigned by the destination.
Preserve null values in the destination table regardless of the settings for default values. When not specified, null values are replaced by default values where applicable.
Obtain a bulk update lock for the duration of the bulk copy operation. When not specified, row locks are used.
When specified, each batch of the bulk-copy operation will occur within a transaction. If you indicate this option and also provide a
object to the constructor, an occurs.
Represents a set of methods for creating instances of the
provider's implementation of the data source classes.
To be added.
Gets an instance of the
. This can be used to retrieve strongly typed data objects.
property to retrieve a **SqlClientFactory** instance, and then return a strongly typed
instance:
```csharp
SqlClientFactory newFactory = SqlClientFactory.Instance;
DbCommand cmd = newFactory.CreateCommand();
```
]]>
Returns a strongly typed
instance.
A new strongly typed instance of
.
instance:
```csharp
SqlClientFactory newFactory = SqlClientFactory.Instance;
DbCommand cmd = newFactory.CreateCommand();
```
]]>
Returns a strongly typed
instance.
A new strongly typed instance of
.
instance:
```csharp
SqlClientFactory newFactory = SqlClientFactory.Instance;
DbCommandBuilder cmd = newFactory.CreateCommandBuilder();
```
]]>
Returns a strongly typed
instance.
A new strongly typed instance of
.
instance:
```csharp
SqlClientFactory newFactory = SqlClientFactory.Instance;
DbConnection cmd = newFactory.CreateConnection();
```
]]>
Returns a strongly typed
instance.
A new strongly typed instance of
.
instance:
```csharp
SqlClientFactory newFactory = SqlClientFactory.Instance;
DbConnectionStringBuilder cmd =
newFactory.CreateConnectionStringBuilder();
```
]]>
Returns a strongly typed
instance.
A new strongly typed instance of
.
instance:
```csharp
SqlClientFactory newFactory = SqlClientFactory.Instance;
DbDataAdapter cmd = newFactory.CreateDataAdapter();
```
]]>
Returns a strongly typed
instance.
A new strongly typed instance of
.
instance:
```csharp
SqlClientFactory newFactory = SqlClientFactory.Instance;
DbParameter cmd = newFactory.CreateParameter();
```
]]>
Represents a SQL client logger.To be added.
Initializes a new instance of the class.To be added.
Gets a value that indicates whether bid tracing is enabled.
if bid tracing is enabled; otherwise, .To be added.
The type to be logged.The logging method.The message to be logged.Logs warning through a specified method of the current instance type.
to log the message; otherwise, .The type to be logged.The logging method.The message to be logged.Logs the specified message if is . if the message is not logged; otherwise, .To be added.
The type to be logged.The logging method.The message to be logged.Logs an error through a specified method of the current instance type.To be added.
The type to be logged.The logging method.The message to be logged.Logs information through a specified method of the current instance type.To be added.
Provides a list of constants for use with the **GetSchema** method to retrieve metadata collections.To be added.
A constant for use with the **GetSchema** method that represents the **Columns** collection.To be added.
A constant for use with the **GetSchema** method that represents the **Databases** collection.To be added.
A constant for use with the **GetSchema** method that represents the **ForeignKeys** collection.To be added.
A constant for use with the **GetSchema** method that represents the **IndexColumns** collection.To be added.
A constant for use with the **GetSchema** method that represents the **Indexes** collection.To be added.
A constant for use with the **GetSchema** method that represents the **ProcedureParameters** collection.To be added.
A constant for use with the **GetSchema** method that represents the **Procedures** collection.To be added.
A constant for use with the **GetSchema** method that represents the **Tables** collection.To be added.
A constant for use with the **GetSchema** method that represents the **UserDefinedTypes** collection.To be added.
A constant for use with the **GetSchema** method that represents the **Users** collection.To be added.
A constant for use with the **GetSchema** method that represents the **ViewColumns** collection.To be added.
A constant for use with the **GetSchema** method that represents the **Views** collection.To be added.
A constant for use with the **GetSchema** method that represents the **AllColumns** collection.To be added.
A constant for use with the **GetSchema** method that represents the **ColumnSetColumns** collection.To be added.
A constant for use with the **GetSchema** method that represents the **StructuredTypeMembers** collection.To be added.
Specifies a value for Attestation Protocol.
If the attestation protocol is not specified. Use this as default value.0
Attestation portocol for Azure Attestation Service1
Attestation protocol for no attestation. Only compatible with Virtualization-based security (VBS) enclaves. An Enclave Attestation Url is not required when using this protocol.2
Attestation protocol for Host Guardian Service3
Specifies a value for IP address preference during a TCP connection.
Connects using IPv4 address(es) first. If the connection fails, try IPv6 address(es), if provided. This is the default value.0
Connect using IPv6 address(es) first. If the connection fails, try IPv4 address(es), if available.1
Connects with IP addresses in the order the underlying platform or operating system provides them.2
These options are used to control encryption behavior of the communication between the server and the client.
property. When converting from a boolean, a value of `true` converts to and a value of `false` converts to . When converting to a boolean, , , and `null` convert to `true` and converts `false`.
]]>
Converts the specified string representation of a logical value to its equivalent.
A string containing the value to convert.
An object that is equivalent to contained in .
Throws exception if provided is not convertible to type.
Converts the specified string representation of a logical value to its equivalent and returns a value that indicates whether the conversion succeeded.
A string containing the value to convert.
An object that is equivalent to contained in . if conversion fails.
if the parameter was converted successfully; otherwise, .
This method does not throw an exception if conversion fails.
Specifies that TLS encryption is optional when connecting to the server. If the server requires encryption, encryption will be negotiated.
Specifies that TLS encryption is required when connecting to the server. If the server doesn't support encryption, the connection will fail.
Enables and requires TDS 8.0, TLS encryption to the server. If the server doesn't support TDS 8.0, TLS encryption, the connection will fail.
The boolean value to be used for implicit comparison.
Enables implicit converstion of a boolean to a . A value of converts to . A value of converts to .
The value to be used for implicit comparison.
Enables implicit converstion of a to a boolean. and convert to . converts to .
Returns the string value of .
Compares the representation of to another .
Returns the hash code of the value.
The implementation of the key store provider for Windows Certificate Store. This class enables using certificates stored in the Windows Certificate Store as column master keys.
For details, see Always Encrypted.
To be added.
The provider name.To be added.
Key store provider for Windows Certificate Store.To be added.
The master key path.The encryption algorithm. Currently, the only valid value is: RSA_OAEP
The encrypted column encryption key.Decrypts the specified encrypted value of a column encryption key. The encrypted value is expected to be encrypted using the certificate with the specified key path and using the specified
algorithm. The format of the key path should be "Local Machine/My/<certificate_thumbprint>" or "Current User/My/<certificate_thumbprint>".
Returns
. The decrypted column encryption key.To be added.
The master key path.The encryption algorithm. Currently, the only valid value is: RSA_OAEP
The plaintext column encryption key.Encrypts a column encryption key using the certificate with the specified key path and using the specified algorithm. The format of the key path should be
"Local Machine/My/<certificate_thumbprint>" or "Current User/My/<certificate_thumbprint>".
Returns
. The encrypted column encryption key.To be added.
The column master key path.
to indicate that the column master key supports enclave computations; otherwise,
.Digitally signs the column master key metadata with the column master key referenced by the
parameter.The signature of the column master key metadata.To be added.
The complete path of an asymmetric key. The path format is specific to a key store provider.A Boolean that indicates if this key can be sent to the trusted enclave.The master key metadata siognature.This function must be implemented by the corresponding Key Store providers. This function should use an asymmetric key identified by a key path and verify the masterkey metadata consisting of (masterKeyPath, allowEnclaveComputations, providerName).A Boolean value that indicates if the master key metadata can be verified based on the provided signature.To be added.
The CMK Store provider implementation for using the Microsoft Cryptography API: Next Generation (CNG) with
Always Encrypted.
A constant string for the provider name 'MSSQL_CNG_STORE'.To be added.
Initializes a new instance of the class.To be added.
The master key path.The encryption algorithm.The encrypted column encryption key.Decrypts the given encrypted value using an asymmetric key specified by the key path and the specified algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier
and should be an asymmetric key stored in the specified CNG key store provider. The valid algorithm used to encrypt/decrypt the CEK is 'RSA_OAEP'.
The decrypted column encryption key.To be added.
The master key path.The encryption algorithm.The plaintext column encryption key.Encrypts the given plain text column encryption key using an asymmetric key specified by the key path and the specified algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier and should be an asymmetric key stored in the specified CNG key store provider. The valid algorithm used to encrypt/decrypt the CEK is 'RSA_OAEP'.The encrypted column encryption key.To be added.
The column master key path. The path format is specific to a key store provider. to indicate that the column master key supports enclave computations; otherwise, .Throws a exception in all cases.The signature of the column master key metadata.
method must be implemented by the corresponding key store providers.
should use an asymmetric key identified by a key path and sign the masterkey metadata consisting
of `masterKeyPath`, `allowEnclaveComputations`, and providerName.
]]>
The complete path of an asymmetric key. The path format is specific to a key store provider.A Boolean that indicates if this key can be sent to the trusted enclave.The master key metadata signature.This function must be implemented by the corresponding Key Store providers. This function should use an asymmetric key identified by a key path and verify the masterkey metadata consisting of (masterKeyPath, allowEnclaveComputations, providerName).A Boolean that indicates if the master key metadata can be verified based on the provided signature.To be added.
The CMK Store provider implementation for using Microsoft CAPI based Cryptographic Service Providers (CSP) with
Always Encrypted.
A constant string for the provider name 'MSSQL_CSP_PROVIDER'.To be added.
Initializes a new instance of the class.To be added.
The master key path.The encryption algorithm.The encrypted column encryption key.Decrypts the given encrypted value using an asymmetric key specified by the key path and algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier and should be an asymmetric key stored in the specified CSP provider. The valid algorithm used to encrypt/decrypt the CEK is 'RSA_OAEP'.The decrypted column encryption key.To be added.
The master key path.The encryption algorithm.The plaintext column encryption key.Encrypts the given plain text column encryption key using an asymmetric key specified by the key path and the specified algorithm. The key path will be in the format of [ProviderName]/KeyIdentifier and should be an asymmetric key stored in the specified CSP provider. The valid algorithm used to encrypt/decrypt the CEK is 'RSA_OAEP'.The encrypted column encryption key.To be added.
The column master key path. The path format is specific to a key store provider. to indicate that the column master key supports enclave computations; otherwise, .Throws a exception in all cases.The signature of the column master key metadata.
method must be implemented by the corresponding key store providers.
should use an asymmetric key identified by a key path and sign the masterkey metadata
consisting of `masterKeyPath`, `allowEnclaveComputations`, and providerName.
]]>
The complete path of an asymmetric key. The path format is specific to a key store provider.A boolean that indicates if this key can be sent to the trusted enclave.Master key metadata signature.This function must be implemented by the corresponding Key Store providers. This function should use an asymmetric key identified by a key path and sign the masterkey metadata consisting of (masterKeyPath, allowEnclaveComputations, providerName).A Boolean that indicates if the master key metadata can be verified based on the provided signature.To be added.
Base class for all key store providers. A custom provider must derive from this class and override its member functions and then register it using
,
or
.
For details see, Always Encrypted.
Initializes a new instance of the SqlColumnEncryptionKeyStoreProviderClass.To be added.
The master key path.The encryption algorithm.The encrypted column encryption key.Decrypts the specified encrypted value of a column encryption key. The encrypted value is expected to be encrypted using the column master key with the specified key path and using the specified algorithm.
Returns . The decrypted column encryption key.To be added.
The master key path.The encryption algorithm.The plaintext column encryption key.Encrypts a column encryption key using the column master key with the specified key path and using the specified algorithm.Returns . The encrypted column encryption key.To be added.
The column master key path. to indicate that the column master key supports enclave computations; otherwise, .When implemented in a derived class, digitally signs the column master key metadata with the column master key referenced by the parameter. The input values used to generate the signature should be the specified values of the and parameters.
The signature of the column master key metadata.
method doesn't break applications that rely on an old API, it throws a
exception by default.
The method will be used by client tools that generate Column Master Keys (CMK) for customers.
must be implemented by the corresponding key store providers that wish to use enclaves with
[Always Encrypted](https://docs.microsoft.com/sql/relational-databases/security/encryption/always-encrypted-database-engine).
]]>
In all cases.
The column master key path.Indicates whether the column master key supports enclave computations.The signature of the column master key metadata.When implemented in a derived class, this method is expected to verify the specified signature is valid for the column master key with the specified key path and the specified enclave behavior. The default implementation throws NotImplementedException.When implemented in a derived class, the method is expected to return true if the specified signature is valid, or false if the specified signature is not valid. The default implementation throws NotImplementedException.To be added.
Gets or sets the lifespan of the decrypted column encryption key in the cache. Once the timespan has elapsed, the decrypted column encryption key is discarded and must be revalidated.
. Any caching implementation should reference the value of this property before caching a column encryption key and not cache it if the value is zero. This will avoid duplicate caching and possible user confusion when they are trying to configure key caching.
]]>
Note that these settings cannot be used to bypass encryption and gain access to plaintext data. For details, see Always Encrypted (Database Engine).
Specifies the connection does not use Always Encrypted. Should be used if no queries sent over the connection access encrypted columns.
Enables Always Encrypted for the query.
Specifies that only the results of the command should be processed by the Always Encrypted routine in the driver. Use this value when the command has no parameters that require encryption.
Specifies that the command should default to the Always Encrypted setting in the connection string.
Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database. This class cannot be inherited.
is created, the read/write properties are set to their initial values. For a list of these values, see the constructor.
features the following methods for executing commands at a SQL Server database:
|Item|Description|
|----------|-----------------|
||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this , generally executing commands such as INSERT, DELETE, UPDATE, and SET statements. Each call to must be paired with a call to which finishes the operation, typically on a separate thread.|
||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this and retrieves one or more results sets from the server. Each call to must be paired with a call to which finishes the operation, typically on a separate thread.|
||Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this . Each call to `BeginExecuteXmlReader` must be paired with a call to `EndExecuteXmlReader`, which finishes the operation, typically on a separate thread, and returns an object.|
||Executes commands that return rows. For increased performance, invokes commands using the Transact-SQL `sp_executesql` system stored procedure. Therefore, might not have the effect that you want if used to execute commands such as Transact-SQL SET statements.|
||Executes commands such as Transact-SQL INSERT, DELETE, UPDATE, and SET statements.|
||Retrieves a single value (for example, an aggregate value) from a database.|
||Sends the to the and builds an object.|
You can reset the property and reuse the object. However, you must close the before you can execute a new or previous command.
If a is generated by the method executing a , the remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server ordinarily closes the . However, the user can reopen the connection and continue.
> [!NOTE]
> Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server.
## Examples
The following example creates a , a , and a . The example reads through the data, writing it to the console. Finally, the example closes the and then the as it exits the `Using` code blocks.
[!code-csharp[SqlCommand Example#1](~/../sqlclient/doc/samples/SqlCommand.cs#1)]
The following sample shows how to create and execute different types of SqlCommand objects.
First you must create the sample database, by executing the following script:
[!code-sql[Setup Database](~/../sqlclient/doc/samples/SqlCommand_Setup.sql#1)]
Next, compile and execute the following:
[!code-csharp[SqlCommand Example#2](~/../sqlclient/doc/samples/SqlCommand_Intro.cs#1)]
]]>
Initializes a new instance of the
class.
.
|Properties|Initial value|
|----------------|-------------------|
||empty string ("")|
||30|
||`CommandType.Text`|
||Null|
You can change the value for any of these properties through a separate call to the property.
## Examples
The following example creates a and sets the `CommandTimeout` property.
[!code-csharp[Classic WebData IDbCommand_CommandTimeout.cs](~/../sqlclient/doc/samples/IDbCommand_CommandTimeout.cs)]
]]>
The text of the query.
Initializes a new instance of the
class with the text of the query.
is created, the following read/write properties are set to initial values.
|Properties|Initial value|
|----------------|-------------------|
||`cmdText`|
||30|
||`CommandType.Text`|
||null|
You can change the value for any of these properties through a separate call to the property.
## Examples
The following example creates a , passing in the connection string and command text.
[!code-csharp[SqlCommand_SqlCommand1](~/../sqlclient/doc/samples/SqlCommand_SqlCommand1.cs#1)]
]]>
The text of the query.
A
that represents the connection to an instance of SQL Server.
Initializes a new instance of the
class with the text of the query and a
.
.
|Properties|Initial value|
|----------------|-------------------|
||`cmdText`|
||30|
||`CommandType.Text`|
||A new that is the value for the `connection` parameter.|
You can change the value for any of these parameters by setting the related property.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlCommand_SqlCommand2.cs](~/../sqlclient/doc/samples/SqlCommand_SqlCommand2.cs#1)]
]]>
The text of the query.
A
that represents the connection to an instance of SQL Server.
The
in which the
executes.
Initializes a new instance of the
class with the text of the query, a
, and the
.
.
|Properties|Initial value|
|----------------|-------------------|
||`cmdText`|
||30|
||`CommandType.Text`|
||A new that is the value for the `connection` parameter.|
You can change the value for any of these parameters by setting the related property.
]]>
The text of the query.
A
that represents the connection to an instance of SQL Server.
The
in which the
executes.
The encryption setting. For more information, see [Always Encrypted](/sql/relational-databases/security/encryption/always-encrypted-database-engine).
Initializes a new instance of the
class with specified command text, connection, transaction, and encryption setting.
To be added.
Gets the column encryption setting for this command.
The column encryption setting for this command.
Gets or sets the Transact-SQL statement, table name or stored procedure to execute at the data source.
The Transact-SQL statement or stored procedure to execute. The default is an empty string.
property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The user may be required to use escape character syntax if the stored procedure name contains any special characters. The command executes this stored procedure when you call one of the `Execute` methods.
The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a Transact-SQL statement or a stored procedure called by a command of `CommandType.Text`. In this case, named parameters must be used. For example:
```sql
SELECT * FROM dbo.Customers WHERE CustomerID = @CustomerID
```
For more information, see [Configuring parameters](/sql/connect/ado-net/configure-parameters).
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlCommand_CommandText](~/../sqlclient/doc/samples/SqlCommand_CommandText.cs)]
]]>
Gets or sets the wait time (in seconds) before terminating the attempt to execute a command and generating an error. The default is 30 seconds.
The time in seconds to wait for the command to execute. The default is 30 seconds.
[!NOTE]
> The property will be ignored during old-style asynchronous method calls such as . It will be honored by the newer async methods such as .
> [!NOTE]
> This property is the cumulative time-out (for all network packets that are read during the invocation of a method) for all network reads during command execution or processing of the results. A time-out can still occur after the first row is returned, and does not include user processing time, only network read time.
For example, with a 30 second time out, if requires two network packets, then it has 30 seconds to read both network packets. If you call again, it will have another 30 seconds to read any data that it requires.
[!code-csharp[SqlCommand CommandTimeout](~/../sqlclient/doc/samples/SqlCommand_CommandTimeout.cs)]
]]>
The value set is less than 0.
Gets or sets a value indicating how the
property is to be interpreted.
One of the
values. The default is
.
property to `StoredProcedure`, you should set the property to the name of the stored procedure. The command executes this stored procedure when you call one of the Execute methods.
The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a SQL Statement or a stored procedure called with a of . In this case, named parameters must be used. For example:
SELECT * FROM Customers WHERE CustomerID = @CustomerID
For more information, see [Configuring parameters](/sql/connect/ado-net/configure-parameters).
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[IDbCommand_CommandTimeout](~/../sqlclient/doc/samples/IDbCommand_CommandTimeout.cs)]
]]>
Gets or sets the
used by this instance of the
.
The connection to a data source. The default value is
.
.
If the property is not null and the transaction has already been committed or rolled back, is set to null.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlCommand_Connection](~/../sqlclient/doc/samples/SqlCommand_Connection.cs)]
]]>
The
property was changed while the command was enlisted in a transaction.
To be added.
To be added.
To be added.
Gets the collection of objects.
The parameters of the SQL statement or stored procedure.
To be added.
To be added.
To be added.
To be added.
Gets or sets a value indicating whether the command object should be visible in a Windows Form Designer control.
A value indicating whether the command object should be visible in a control. The default is
.
To be added.
Gets or sets a value indicating whether the command object should optimize parameter performance by disabling Output and InputOutput directions when submitting the command to the SQL Server.
A value indicating whether the command object should optimize parameter performance by disabling Output and InputOuput parameter directions when submitting the command to the SQL Server.
The default is .
[!NOTE]
If the option is enabled and a parameter with Direction Output or InputOutput is present in the Parameters collection an InvalidOperationException will be thrown when the command is executed.
]]>
Gets the
.
The parameters of the Transact-SQL statement or stored procedure. The default is an empty collection.
[!NOTE]
> If the parameters in the collection do not match the requirements of the query to be executed, an error may result.
For more information, see [Configuring parameters](/sql/connect/ado-net/configure-parameters).
## Examples
The following example demonstrates how to create a and add parameters to the .
[!code-csharp[SqlParameterCollection.AddWithValue#1](~/../sqlclient/doc/samples/SqlParameterCollection_AddWithValue.cs#1)]
]]>
Gets or sets the
within which the
executes.
The
. The default value is
.
property if it is already set to a specific value, and the command is in the process of executing. If you set the transaction property to a object that is not connected to the same as the object, an exception is thrown the next time that you attempt to execute a statement.
]]>
Gets or sets how command results are applied to the when used by the **Update** method of the .
One of the values.
value is **Both** unless the command is automatically generated (as in the case of the ), in which case the default is **None**.
For more information about using the **UpdatedRowSource** property, see [DataAdapter Parameters](/sql/connect/ado-net/dataadapter-parameters).
]]>
Occurs when the execution of a Transact-SQL statement completes.
To be added.
Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this
.
An
that can be used to poll or wait for results, or both; this value is also needed when invoking
, which returns the number of affected rows.
method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished.
Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous.
Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned .
This method ignores the property.
## Examples
The following console application creates updates data within the **AdventureWorks** sample database, doing its work asynchronously. In order to emulate a long-running process, this example inserts a WAITFOR statement in the command text. Normally, you would not take efforts to make your commands run slower, but doing this in this case makes it easier to demonstrate the asynchronous behavior.
[!code-csharp[SqlCommand_BeginExecuteNonQuery](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteNonQuery.cs)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Any error that occurred while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
- or -
is set to true and a parameter with direction Output or InputOutput has been added to the collection.
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An
delegate that is invoked when the command's execution has completed. Pass
(
in Microsoft Visual Basic) to indicate that no callback is required.
A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the
property.
Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this
, given a callback procedure and state information.
An
that can be used to poll or wait for results, or both; this value is also needed when invoking
, which returns the number of affected rows.
method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that does not return rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished.
The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `asyncStateObject` parameter, and your callback procedure can retrieve this information using the property.
Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous.
Because the callback procedure executes from within a background thread supplied by the Microsoft .NET common language runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure; should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior.
All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure.
This method ignores the property.
## Examples
The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of several seconds (emulating a long-running command).
This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called.
To set up this example, create a new Windows application. Put a control and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment.
[!code-csharp[DataWorks SqlCommand_BeginExecuteNonQueryForm#1](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteNonQueryForm.cs)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Any error that occurred while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
- or -
is set to true and a parameter with direction Output or InputOutput has been added to the collection.
Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this
, and retrieves one or more result sets from the server.
An
that can be used to poll or wait for results, or both; this value is also needed when invoking
, which returns a
instance that can be used to retrieve the returned rows.
method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished.
Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks.
Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned .
If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries.
This method ignores the property.
## Examples
The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. As soon as the process has completed, the code retrieves the and displays its contents.
[!code-csharp[SqlCommand_BeginExecuteReader#1](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteReader.cs)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Any error that occurred while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
- or -
is set to true and a parameter with direction Output or InputOutput has been added to the collection.
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An
delegate that is invoked when the command's execution has completed. Pass
(
in Microsoft Visual Basic) to indicate that no callback is required.
A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the
property.
Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this
and retrieves one or more result sets from the server, given a callback procedure and state information.
An
that can be used to poll, wait for results, or both; this value is also needed when invoking
, which returns a
instance which can be used to retrieve the returned rows.
method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed cause the object to block until the execution is finished.
The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property.
Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks.
Because the callback procedure executes from within a background thread supplied by the Microsoft .NET runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure; should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior.
All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure.
If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries.
This method ignores the property.
## Examples
The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). Because the sample executes the command asynchronously, the form remains responsive while awaiting the results. This example passes the executing object as the `stateObject` parameter; doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to .
This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called.
To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment.
[!code-csharp[SqlCommand_BeginExecuteReaderAsync.cs](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteReaderAsync.cs)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Any error that occurred while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
- or -
is set to true and a parameter with direction Output or InputOutput has been added to the collection.
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An
delegate that is invoked when the command's execution has completed. Pass
(
in Microsoft Visual Basic) to indicate that no callback is required.
A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the
property.
One of the
values, indicating options for statement execution and data retrieval.
Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this
, using one of the
values, and retrieving one or more result sets from the server, given a callback procedure and state information.
An
that can be used to poll or wait for results, or both; this value is also needed when invoking
, which returns a
instance which can be used to retrieve the returned rows.
method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished.
The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property.
The `behavior` parameter lets you specify options that control the behavior of the command and its connection. These values can be combined together (using the programming language's `Or` operator); generally, developers use the `CloseConnection` value to make sure that the connection is closed by the runtime when the is closed. Developers can also optimize the behavior of the by specifying the `SingleRow` value when it is known in advance that the Transact-SQL statement or stored procedure only returns a single row.
Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks.
Because the callback procedure executes from within a background thread supplied by the Microsoft .NET common language runtime, it is very important that you take a rigorous approach to handling cross-thread interactions from within your applications. For example, you must not interact with a form's contents from within your callback procedure--should you have to update the form, you must switch back to the form's thread in order to do your work. The example in this topic demonstrates this behavior.
All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure.
If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries.
This method ignores the property.
## Examples
The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). Because the sample executes the command asynchronously, the form remains responsive while awaiting the results. This example passes the executing object as the `stateObject` parameter; doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to .
This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called.
To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment.
This example passes the `CommandBehavior.CloseConnection` value in the `behavior` parameter, causing the returned to automatically close its connection when it is closed.
[!code-csharp[SqlCommand_BeginExecuteReaderAsyncBehavior](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteReaderAsyncBehavior.cs)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Any error that occurred while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
- or -
is set to true and a parameter with direction Output or InputOutput has been added to the collection.
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
One of the
values, indicating options for statement execution and data retrieval.
Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this
using one of the
values.
An
that can be used to poll, wait for results, or both; this value is also needed when invoking
, which returns a
instance that can be used to retrieve the returned rows.
method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the returned by the command. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished.
The `behavior` parameter lets you specify options that control the behavior of the command and its connection. These values can be combined together (using the programming language's `OR` operator); generally, developers use the `CommandBehavior.CloseConnection` value to make sure that the connection is closed by the runtime when the is closed.
Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous. This means that calls to may block if more data is required and the underlying network's read operation blocks.
Because this overload does not support a callback procedure, developers must either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned .
If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries.
This method ignores the property.
## Examples
The following console application starts the process of retrieving a data reader asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. Once the process has completed, the code retrieves the and displays its contents.
This example also passes the `CommandBehavior.CloseConnection` and `CommandBehavior.SingleRow` values in the behavior parameter, causing the connection to be closed with the returned is closed, and to optimize for a single row result.
[!code-csharp[SqlCommand_BeginExecuteReaderAsyncSimple](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteReaderAsyncSimple.cs)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Any error that occurred while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
- or -
is set to true and a parameter with direction Output or InputOutput has been added to the collection.
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this
and returns results as an
object.
An
that can be used to poll or wait for results, or both; this value is also needed when invoking
, which returns a single XML value.
method starts the process of asynchronously executing a Transact-SQL statement that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the `EndExecuteXmlReader` method to finish the operation and retrieve the XML returned by the command. The method returns immediately, but until the code executes the corresponding `EndExecuteXmlReader` method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the `EndExecuteXmlReader` before the command's execution is completed causes the object to block until the execution is finished.
The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, `CommandText` can also specify a statement that returns `ntext` data that contains valid XML.
A typical query can be formatted as in the following C# example:
```csharp
SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM dbo.Contact FOR XML AUTO, XMLDATA", SqlConn);
```
This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the `EndExecuteXmlReader` method attaches the to the value on the first row, and discards the rest of the result set.
The multiple active result set (MARS) feature lets multiple actions use the same connection.
Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters are sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous. Although command execution is asynchronous, value fetching is still synchronous.
Because this overload does not support a callback procedure, developers need to either poll to determine whether the command has completed, using the property of the returned by the method; or wait for the completion of one or more commands using the property of the returned .
If you use or to access XML data, SQL Server returns any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries.
This method ignores the property.
## Examples
The following console application starts the process of retrieving XML data asynchronously. While waiting for the results, this simple application sits in a loop, investigating the property value. Once the process has completed, the code retrieves the XML and displays its contents.
[!code-csharp[SqlCommand_BeginExecuteXmlReader#1]((~/../sqlclient/doc/samples/SqlCommand_BeginExecuteXmlReader.cs)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Any error that occurred while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
- or -
is set to true and a parameter with direction Output or InputOutput has been added to the collection.
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An
delegate that is invoked when the command's execution has completed. Pass
(
in Microsoft Visual Basic) to indicate that no callback is required.
A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback procedure using the
property.
Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this
and returns results as an
object, using a callback procedure.
An
that can be used to poll, wait for results, or both; this value is also needed when the
is called, which returns the results of the command as XML.
method starts the process of asynchronously executing a Transact-SQL statement or stored procedure that returns rows as XML, so that other tasks can run concurrently while the statement is executing. When the statement has completed, developers must call the method to finish the operation and retrieve the requested XML data. The method returns immediately, but until the code executes the corresponding method call, it must not execute any other calls that start a synchronous or asynchronous execution against the same object. Calling the before the command's execution is completed causes the object to block until the execution is finished.
The property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, `CommandText` can also specify a statement that returns data that contains valid XML. This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set.
A typical query can be formatted as in the following C# example:
```csharp
SqlCommand command = new SqlCommand("SELECT ContactID, FirstName, LastName FROM Contact FOR XML AUTO, XMLDATA", SqlConn);
```
This method can also be used to retrieve a single-row, single-column result set. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set.
The multiple active result set (MARS) feature lets multiple actions use the same connection.
The `callback` parameter lets you specify an delegate that is called when the statement has completed. You can call the method from within this delegate procedure, or from any other location within your application. In addition, you can pass any object in the `stateObject` parameter, and your callback procedure can retrieve this information using the property.
Note that the command text and parameters are sent to the server synchronously. If a large command or many parameters is sent, this method may block during writes. After the command is sent, the method returns immediately without waiting for an answer from the server--that is, reads are asynchronous.
All errors that occur during the execution of the operation are thrown as exceptions in the callback procedure. You must handle the exception in the callback procedure, not in the main application. See the example in this topic for additional information on handling exceptions in the callback procedure.
If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries.
This method ignores the property.
## Examples
The following Windows application demonstrates the use of the method, executing a Transact-SQL statement that includes a delay of a few seconds (emulating a long-running command). This example passes the executing object as the `stateObject` parameter--doing so makes it simple to retrieve the object from within the callback procedure, so that the code can call the method corresponding to the initial call to .
This example demonstrates many important techniques. This includes calling a method that interacts with the form from a separate thread. In addition, this example demonstrates how you must block users from executing a command multiple times concurrently, and how you must make sure that the form does not close before the callback procedure is called.
To set up this example, create a new Windows application. Put a control, a control, and a control on the form (accepting the default name for each control). Add the following code to the form's class, modifying the connection string as needed for your environment.
[!code-csharp[SqlCommand_BeginExecuteXmlReaderAsync](~/../sqlclient/doc/samples/SqlCommand_BeginExecuteXmlReaderAsync.cs)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Any error that occurred while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
- or -
is set to true and a parameter with direction Output or InputOutput has been added to the collection.
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
Tries to cancel the execution of a
.
, then call (implicitly or explicitly) before calling , and then call , the cancel command will not be sent to SQL Server and the result set can continue to stream after you call . To avoid this, make sure that you call before closing the reader or connection.
## Examples
The following example demonstrates the use of the method.
[!code-csharp[SqlCommand_Cancel](~/../sqlclient/doc/samples/SqlCommand_Cancel.cs)]
]]>
Creates a new
object that is a copy of the current instance.
A new
object that is a copy of this instance.
To be added.
To be added.
To be added.
To be added.
Creates a new instance of a
object.
A
object.
method is a strongly-typed version of .
]]>
Creates a new instance of a object.
A object.
To be added.
The
returned by the call to
.
Finishes asynchronous execution of a Transact-SQL statement.
The number of rows affected (the same behavior as
).
to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called.
## Examples
For examples demonstrating the use of the method, see .
]]>
parameter is null (
in Microsoft Visual Basic)
was called more than once for a single command execution, or the method was mismatched against its execution method (for example, the code called
to complete execution of a call to
.
The amount of time specified in
elapsed and the asynchronous operation specified with
is not complete.
-or-
In some situations,
can be set to
incorrectly. If this occurs and
is called, EndExecuteNonQuery could raise a SqlException error if the amount of time specified in
elapsed and the asynchronous operation specified with
is not complete. To correct this situation, you should either increase the value of CommandTimeout or reduce the work being done by the asynchronous operation.
The
returned by the call to
.
Finishes asynchronous execution of a Transact-SQL statement, returning the requested
.
A
object that can be used to retrieve the requested rows.
to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called.
## Examples
For examples demonstrating the use of the method, see .
]]>
parameter is null (
in Microsoft Visual Basic)
was called more than once for a single command execution, or the method was mismatched against its execution method (for example, the code called
to complete execution of a call to
.
The
returned by the call to
.
Finishes asynchronous execution of a Transact-SQL statement, returning the requested data as XML.
An
object that can be used to fetch the resulting XML data.
to execute a Transact-SQL statement, you must call in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete. Users can verify that the command has completed its operation by using the instance returned by the method. If a callback procedure was specified in the call to , this method must be called.
## Examples
For examples demonstrating the use of the method, see .
]]>
parameter is null (
in Microsoft Visual Basic)
was called more than once for a single command execution, or the method was mismatched against its execution method (for example, the code called
to complete execution of a call to
.
To be added.
To be added.
To be added.
To be added.
To be added.
To be added.
To be added.
To be added.
To be added.
Executes a Transact-SQL statement against the connection and returns the number of rows affected.
The number of rows affected.
to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a by executing UPDATE, INSERT, or DELETE statements.
Although the returns no rows, any output parameters or return values mapped to parameters are populated with data.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1.
When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers.
When SET NOCOUNT ON is set on the connection (before or as part of executing the command, or as part of a trigger initiated by the execution of the command) the rows affected by individual statements stop contributing to the count of rows affected that is returned by this method.
If no statements are detected that contribute to the count, the return value is -1. If a rollback occurs, the return value is also -1.
## Examples
The following example creates a and then executes it using . The example is passed a string that is a Transact-SQL statement (such as UPDATE, INSERT, or DELETE) and a string to use to connect to the data source.
[!code-csharp[SqlCommand_ExecuteNonQuery](~/../sqlclient/doc/samples/SqlCommand_ExecuteNonQuery.cs)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The cancellation instruction.
An asynchronous version of
, which executes a Transact-SQL statement against the connection and returns the number of rows affected. The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
[!NOTE]
> For long running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method.
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Calling
more than once for the same instance before task completion.
-or-
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
SQL Server returned an error while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
Sends the
to the
and builds a
.
A
object.
property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The command executes this stored procedure when you call .
> [!NOTE]
> If a transaction is deadlocked, an exception may not be thrown until is called.
The multiple active result set (MARS) feature allows for multiple actions using the same connection.
If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries.
## Examples
The following example creates a , and then executes it by passing a string that is a Transact-SQL SELECT statement, and a string to use to connect to the data source.
[!code-csharp[SqlCommand_ExecuteReader](~/../sqlclient/doc/samples/SqlCommand_ExecuteReader.cs)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The current state of the connection is closed.
requires an open
.
-or-
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
One of the
values.
Sends the
to the
, and builds a
using one of the
values.
A
object.
property is set to `StoredProcedure`, the property should be set to the name of the stored procedure. The command executes this stored procedure when you call .
> [!NOTE]
> Use to retrieve large values and binary data. Otherwise, an might occur and the connection will be closed.
The multiple active result set (MARS) feature allows for multiple actions using the same connection.
If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries.
## Examples
The following example creates a , and then executes it by passing a string that is a Transact-SQL SELECT statement, and a string to use to connect to the data source. is set to .
[!code-csharp[SqlCommand_ExecuteReader2](~/../sqlclient/doc/samples/SqlCommand_ExecuteReader2.cs#1)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An asynchronous version of
, which sends the
to the
and builds a
. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
[!NOTE]
> For long running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method.
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
An invalid
value.
Calling
more than once for the same instance before task completion.
-or-
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
SQL Server returned an error while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
Options for statement execution and data retrieval. When is set to
,
reads the entire row before returning a complete Task.
An asynchronous version of
, which sends the
to the
, and builds a
. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
An invalid
value.
Calling
more than once for the same instance before task completion.
-or-
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
SQL Server returned an error while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
Options for statement execution and data retrieval. When is set to
,
reads the entire row before returning a complete Task.
The cancellation instruction.
An asynchronous version of
, which sends the
to the
, and builds a
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
An invalid
value.
Calling
more than once for the same instance before task completion.
-or-
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
SQL Server returned an error while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The cancellation instruction.
An asynchronous version of
, which sends the
to the
and builds a
.
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
An invalid
value.
Calling
more than once for the same instance before task completion.
-or-
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
SQL Server returned an error while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
The first column of the first row in the result set, or a null reference (
in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.
method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the method, and then performing the operations that you need to generate the single value using the data returned by a .
A typical query can be formatted as in the following C# example:
```csharp
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();
```
## Examples
The following example creates a and then executes it using . The example is passed a string representing a new value to be inserted into a table, and a string to use to connect to the data source. The function returns the new **Identity** column value if a new row was inserted, 0 on failure.
[!code-csharp[SqlCommand.ExecuteScalar#1](~/../sqlclient/doc/samples/SqlCommand_ExecuteScalar.cs#1)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The cancellation instruction.
An asynchronous version of
, which executes the query asynchronously and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
[!NOTE]
> For long running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method.
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Calling
more than once for the same instance before task completion.
-or-
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
SQL Server returned an error while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
Sends the
to the
and builds an
object.
An
object.
property ordinarily specifies a Transact-SQL statement with a valid FOR XML clause. However, can also specify a statement that returns `ntext` or `nvarchar` data that contains valid XML, or the contents of a column defined with the `xml` data type.
A typical query can be formatted as in the following Microsoft Visual C# example:
```csharp
SqlCommand command = new SqlCommand("SELECT * FROM dbo.Customers FOR XML AUTO, XMLDATA", SqlConn);
```
This method can also be used to retrieve a single-row, single-column result set that contains XML data. In this case, if more than one row is returned, the method attaches the to the value on the first row, and discards the rest of the result set.
The multiple active result set (MARS) feature allows for multiple actions using the same connection.
If you use or to access XML data, SQL Server will return any XML results greater than 2,033 characters in length in multiple rows of 2,033 characters each. To avoid this behavior, use or to read FOR XML queries.
## Examples
The following example creates a and then executes it using . The example is passed a string that is a Transact-SQL FOR XML SELECT statement, and a string to use to connect to the data source.
[!code-csharp[SqlCommand_ExecuteXmlReader#1](~/../sqlclient/doc/samples/SqlCommand_ExecuteXmlReader.cs#1)]
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
An exception occurred while executing the command against a locked row. This exception is not generated when you are using Microsoft .NET Framework version 1.0.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An asynchronous version of
, which sends the
to the
and builds an
object.
Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
[!NOTE]
> For long running queries on the server, consider using due to a known issue with canceling queries via a cancellation token. Also, consider canceling execution using the method.
]]>
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Calling
more than once for the same instance before task completion.
-or-
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
SQL Server returned an error while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The cancellation instruction.
An asynchronous version of
, which sends the
to the
and builds an
object.
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.
A task representing the asynchronous operation.
A
other than **Binary** or **VarBinary** was used when
was set to
. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
-or-
A
other than **Char**, **NChar**, **NVarChar**, **VarChar**, or **Xml** was used when
was set to
.
-or-
A
other than **Xml** was used when
was set to
.
Calling
more than once for the same instance before task completion.
-or-
The
closed or dropped during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
SQL Server returned an error while executing the command text.
-or-
A timeout occurred during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
An error occurred in a
,
or
object during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
The
,
or
object was closed during a streaming operation. For more information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
Creates a prepared version of the command on an instance of SQL Server.
is set to `StoredProcedure`, the call to should succeed, although it may cause a no-op.
Before you call , specify the data type of each parameter in the statement to be prepared. For each parameter that has a variable length data type, you must set the property to the maximum size needed. returns an error if these conditions are not met.
> [!NOTE]
> If the database context is changed by executing the Transact-SQL `USE ` statement, or by calling the method, then must be called a second time.
If you call an `Execute` method after calling , any parameter value that is larger than the value specified by the property is automatically truncated to the original specified size of the parameter, and no truncation errors are returned.
Output parameters (whether prepared or not) must have a user-specified data type. If you specify a variable length data type, you must also specify the maximum .
Prior to Visual Studio 2010, threw an exception. Beginning in Visual Studio 2010, this method does not throw an exception.
## Examples
The following example demonstrates the use of the method.
[!code-csharp[SqlCommand.Prepare#1](~/../sqlclient/doc/samples/SqlCommand_Prepare.cs#1)]
]]>
Gets or sets a value that specifies the
object bound to this command.
When set to null (default), no notification should be requested.
Dictionary of custom column encryption key providersRegisters the encryption key store providers on the instance. If this function has been called, any providers registered using the or
methods will be ignored. This function can be called more than once. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set.
A null dictionary was provided.
-or-
A string key in the dictionary was null or empty.
-or-
A value in the dictionary was null.
A string key in the dictionary started with "MSSQL_". This prefix is reserved for system providers.
Resets the property to its default value.
is 30 seconds.
]]>
Gets or sets a value that specifies the
object bound to this command.
When set to null (default), the default non-retriable provider will be used.
type.
2. Create a by using one of the following static methods of the class:
-
-
-
-
3. Assign the object to the `RetryLogicProvider` property.
> [!NOTE]
> Detecting retriable exceptions is a vital part of the retry pattern. Before applying retry logic, it is important to investigate exceptions and choose a retry provider that best fits your scenario. First, log your exceptions and find transient faults.
> [!NOTE]
> The command **timeout** restarts for each execution of a command within the retry logic and after applying the retry time delay. There is no timing overlap between these two actions.
> [!NOTE]
> The default retry logic provider is not enabled unless it is configured in an application configuration file. For more information, see [Configurable retry logic configuration file](/sql/connect/ado-net/configurable-retry-logic-config-file-sqlclient).
> [!CAUTION]
> A command with isn't compatible with the built-in retry logic. The underlying connection is immediately closed after the first execution attempt and is no longer available for subsequent retries.
## Example
The following sample creates a database and establishes an active connection to it. While the database has an active connection, it tries to drop it with a new and a that uses a . You should kill the active connection through the database to unblock the second command before exceeding the number of retries.
The blocking connection simulates a situation like a command still running in the database and unlikely to finish.
[!code-csharp[SqlConfigurableRetryLogic_SqlCommand#1](~/../sqlclient/doc/samples/SqlConfigurableRetryLogic_SqlCommand.cs#1)]
### How to use with synchronous commands
[!code-csharp[SqlConfigurableRetryLogic_SqlCommand#2](~/../sqlclient/doc/samples/SqlConfigurableRetryLogic_SqlCommand.cs#2)]
### How to use with asynchoronous commands
[!code-csharp[SqlConfigurableRetryLogic_SqlCommand#3](~/../sqlclient/doc/samples/SqlConfigurableRetryLogic_SqlCommand.cs#3)]
### How to use with legacy asynchronous commands
Besides assigning the provider to the command and executing the command, it's possible to run it directly using the following methods:
-
-
-
[!code-csharp[SqlConfigurableRetryLogic_SqlCommand#4](~/../sqlclient/doc/samples/SqlConfigurableRetryLogic_SqlCommand.cs#4)]
> [!NOTE]
> The Asynchronous Programming Model (APM) is a legacy pattern that uses a pair of methods starting with `Begin` and `End`, and an interface called `IAsyncResult`. It's not recommended to use this pattern in new applications. These methods are for backwards compatibility.
]]>
To be added.
To be added.
To be added.
Automatically generates single-table commands that are used to reconcile changes made to a
with the associated SQL Server database. This class cannot be inherited.
does not automatically generate the Transact-SQL statements required to reconcile changes made to a with the associated instance of SQL Server. However, you can create a object to automatically generate Transact-SQL statements for single-table updates if you set the property of the . Then, any additional Transact-SQL statements that you do not set are generated by the .
The registers itself as a listener for events whenever you set the property. You can only associate one or object with each other at one time.
To generate INSERT, UPDATE, or DELETE statements, the uses the property to retrieve a required set of metadata automatically. If you change the after the metadata has been retrieved, such as after the first update, you should call the method to update the metadata.
The `SelectCommand` must also return at least one primary key or unique column. If none are present, an **InvalidOperation** exception is generated, and the commands are not generated.
The also uses the , , and properties referenced by the . The user should call if one or more of these properties are modified, or if the itself is replaced. Otherwise the , , and properties retain their previous values.
If you call , the is disassociated from the , and the generated commands are no longer used.
## Examples
The following example uses the , along and , to select rows from a data source. The example is passed a connection string, a query string that is a Transact-SQL SELECT statement, and a string that is the name of the database table. The example then creates a .
[!code-csharp[SqlCommandBuilder#1](~/../sqlclient/doc/samples/SqlCommandBuilder.cs#1)]
]]>
Initializes a new instance of the
class.
To be added.
The name of the
.
Initializes a new instance of the
class with the associated
object.
registers itself as a listener for events that are generated by the specified in this property.
When you create a new instance of , any existing associated with this is released.
]]>
Sets or gets the
for an instance of the
class.
A
object.
To be added.
Sets or gets a string used as the catalog separator for an instance of the
class.
A string that indicates the catalog separator for use with an instance of the
class.
To be added.
Gets or sets a object for which Transact-SQL statements are automatically generated.A object.
registers itself as a listener for events that are generated by the specified in this property.
When you create a new instance of , any existing associated with this is released.
]]>
The referencing the stored procedure from which the parameter information is to be derived. The derived parameters are added to the collection of the .Retrieves parameter information from the stored procedure specified in the and populates the collection of the specified object.
with arbitrary Transact-SQL statements, such as a parameterized SELECT statement.
For more information, see [Configuring parameters](/sql/connect/ado-net/configure-parameters).
]]>
The command text is not a valid stored procedure name.
Gets or sets the starting character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens.The starting character or characters to use. The default is an empty string.
[!NOTE]
> Although you cannot change the or properties after an insert, update, or delete command has been generated, you can change their settings after calling the `Update` method of a DataAdapter.
]]>
This property cannot be changed after an INSERT, UPDATE, or DELETE command has been generated.
Gets or sets the ending character or characters to use when specifying SQL Server database objects, such as tables or columns, whose names contain characters such as spaces or reserved tokens.The ending character or characters to use. The default is an empty string.
[!NOTE]
> Although you cannot change the or properties after an insert, update, or delete operation has been generated, you can change their settings after calling the `Update` method of a DataAdapter.
]]>
This property cannot be changed after an insert, update, or delete command has been generated.
Gets or sets the character to be used for the separator between the schema identifier and any other identifiers.The character to be used as the schema separator.
To be added.
To be added.
To be added.
To be added.
To be added.
To be added.
Gets the automatically generated object required to perform deletions on the database.The automatically generated object required to perform deletions.
method for informational or troubleshooting purposes because it returns the object to be executed.
You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the .
After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or .
For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders).
]]>
If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on.Gets the automatically generated object that is required to perform deletions on the database.The automatically generated object that is required to perform deletions.
method for informational or troubleshooting purposes because it returns the object to be executed.
You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the .
After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The SQL statements are first generated when the application calls either or .
The default behavior, when generating parameter names, is to use `@p1`, `@p2`, and so on for the various parameters. Passing `true` for the `useColumnsForParameterNames` parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met:
- The returned from the **GetSchema** method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name.
- The generated parameter name meets the criteria specified in the returned from the **GetSchema** method call and found in the collection regular expression.
- A returned from the **GetSchema** method call and found in the collection is specified.
For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders).
]]>
Gets the automatically generated object required to perform insertions on the database.The automatically generated object required to perform insertions.
method for informational or troubleshooting purposes because it returns the object to be executed.
You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the .
After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or .
For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders).
]]>
If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on.Gets the automatically generated object that is required to perform insertions on the database.The automatically generated object that is required to perform insertions.
method for informational or troubleshooting purposes because it returns the object to be executed.
You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the .
After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or .
The default behavior, when generating parameter names, is to use `@p1`, `@p2`, and so on for the various parameters. Passing `true` for the `useColumnsForParameterNames` parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met:
- The returned from the **GetSchema** method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name.
- The generated parameter name meets the criteria specified in the returned from the **GetSchema** method call and found in the collection regular expression.
- A returned from the **GetSchema** method call and found in the collection is specified.
For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders).
]]>
To be added.To be added.To be added.To be added.
To be added.To be added.To be added.To be added.
To be added.To be added.To be added.To be added.
To be added.To be added.To be added.To be added.
Gets the automatically generated object required to perform updates on the database.The automatically generated object that is required to perform updates.
method for informational or troubleshooting purposes because it returns the object to be executed.
You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the .
After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or .
For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders).
]]>
If , generate parameter names matching column names if possible. If , generate @p1, @p2, and so on.Gets the automatically generated object required to perform updates on the database.The automatically generated object required to perform updates.
method for informational or troubleshooting purposes because it returns the object to be executed.
You can also use as the basis of a modified command. For example, you might call and modify the value, and then explicitly set that on the .
After the Transact-SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the will still be using information from the previous statement, which might not be correct. The Transact-SQL statements are first generated when the application calls either or .
The default behavior, when generating parameter names, is to use `@p1`, `@p2`, and so on for the various parameters. Passing `true` for the `useColumnsForParameterNames` parameter lets you force the to generate parameters based on the column names instead. This succeeds only if the following conditions are met:
- The returned from the **GetSchema** method call and found in the collection has been specified and its length is equal to or greater than the generated parameter name.
- The generated parameter name meets the criteria specified in the returned from the **GetSchema** method call and found in the collection regular expression.
- A returned from the **GetSchema** method call and found in the collection is specified.
For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders).
]]>
To be added.To be added.To be added.To be added.
To be added.To be added.To be added.To be added.
To be added.To be added.To be added.
The identifier that will have its embedded quotes removed.Given a quoted identifier, returns the correct unquoted form of that identifier. This includes correctly unescaping any embedded quotes in the identifier.The unquoted identifier, with embedded quotes properly unescaped.To be added.Connecting and Retrieving Data in ADO.NETUsing the .NET Framework Data Provider for SQL ServerOverview of the SqlClient driver
Represents a connection to a SQL Server database. This class cannot be inherited.
object represents a unique session to a SQL Server data source. With a client/server database system, it is equivalent to a network connection to the server. is used together with and to increase performance when connecting to a Microsoft SQL Server database. For all third-party SQL Server products and other OLE DB-supported data sources, use .
When you create an instance of , all properties are set to their initial values. For a list of these values, see the constructor.
See for a list of the keywords in a connection string.
If the goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling `Close` or `Dispose`. `Close` and `Dispose` are functionally equivalent. If the connection pooling value `Pooling` is set to `true` or `yes`, the underlying connection is returned back to the connection pool. On the other hand, if `Pooling` is set to `false` or `no`, the underlying connection to the server is actually closed.
> [!NOTE]
> Login and logout events will not be raised on the server when a connection is fetched from or returned to the connection pool, because the connection is not actually closed when it is returned to the connection pool. For more information, see [SQL Server Connection Pooling (ADO.NET)](/sql/connect/ado-net/sql-server-connection-pooling).
To ensure that connections are always closed, open the connection inside of a `using` block, as shown in the following code fragment. Doing so ensures that the connection is automatically closed when the code exits the block.
```vb
Using connection As New SqlConnection(connectionString)
connection.Open()
' Do work here; connection closed on following line.
End Using
```
```csharp
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
```
> [!NOTE]
> To deploy high-performance applications, you must use connection pooling. When you use the .NET Framework Data Provider for SQL Server, you do not have to enable connection pooling because the provider manages this automatically, although you can modify some settings. For more information, see [SQL Server Connection Pooling (ADO.NET)](/sql/connect/ado-net/sql-server-connection-pooling).
If a is generated by the method executing a , the remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server ordinarily closes the . However, the user can reopen the connection and continue.
An application that creates an instance of the object can require all direct and indirect callers to have sufficient permission to the code by setting declarative or imperative security demands. makes security demands using the object. Users can verify that their code has sufficient permissions by using the object. Users and administrators can also use the [Caspol.exe (Code Access Security Policy Tool)](/dotnet/framework/tools/caspol-exe-code-access-security-policy-tool) to modify security policy at the machine, user, and enterprise levels. For more information, see [Security in .NET](/dotnet/standard/security/). For an example demonstrating how to use security demands, see [Code Access Security and ADO.NET](/dotnet/framework/data/adonet/code-access-security).
For more information about handling warning and informational messages from the server, see [Connection Events](/sql/connect/ado-net/connection-events). For more information about SQL Server engine errors and error messages, see [Database Engine Events and Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors).
> [!CAUTION]
> You can force TCP instead of shared memory. You can do that by prefixing tcp: to the server name in the connection string or you can use localhost.
## Examples
The following example creates a and a . The is opened and set as the for the . The example then calls . To accomplish this, the is passed a connection string and a query string that is a Transact-SQL INSERT statement. The connection is closed automatically when the code exits the using block.
[!code-csharp[SqlCommand_ExecuteNonQuery Example#1](~/../sqlclient/doc/samples/SqlCommand_ExecuteNonQuery.cs#1)]
]]>
Initializes a new instance of the class.
is created, the read/write properties are set to the following initial values unless they are specifically set using their associated keywords in the property.
|Properties|Initial value|
|----------------|-------------------|
||empty string ("")|
||15|
||empty string ("")|
||empty string ("")|
You can change the value for these properties only by using the property. The class provides functionality for creating and managing the contents of connection strings.
## Examples
The following example creates and opens a .
[!code-csharp[SqlConnection_SqlConnection Example#1](~/../sqlclient/doc/samples/SqlConnection_SqlConnection.cs#1)]
]]>
The connection used to open the SQL Server database.Initializes a new instance of the class when given a string that contains the connection string.
is created, the read/write properties are set to the following initial values unless they are specifically set using their associated keywords in the property.
|Properties|Initial value|
|----------------|-------------------|
||`connectionString`|
||15|
||empty string ("")|
||empty string ("")|
You can change the value for these properties only by using the property. The class provides functionality for creating and managing the contents of connection strings.
## Examples
The following example creates and opens a .
[!code-csharp[SqlConnection_SqlConnection1 Example#1](~/../sqlclient/doc/samples/SqlConnection_SqlConnection1.cs#1)]
]]>
The supplied connection string argument failed validation.
A connection string that does not use any of the following connection string keywords: , , or ; or that does not use .A object. If is null, is functionally equivalent to .Initializes a new instance of the class given a connection string, that does not use and a object that contains the user ID and password.To be added.The supplied arguments failed validation, including validation.
Gets or sets the time-to-live for column encryption key entries in the column encryption key cache for the Always Encrypted feature. The default value is 2 hours. 0 means no caching at all.The time interval.To be added.
Gets or sets a value that indicates whether query metadata caching is enabled (true) or not (false) for parameterized queries running against Always Encrypted enabled databases. The default value is true.Returns true if query metadata caching is enabled; otherwise false. true is the default.
Allows you to set a list of trusted key paths for a database server. If while processing an application query the driver receives a key path that is not on the list, the query will fail. This property provides additional protection against security attacks that involve a compromised SQL Server providing fake key paths, which may lead to leaking key store credentials.The list of trusted master key paths for the column encryption.To be added.
Dictionary of custom column encryption key store providers
Registers the column encryption key store providers. This function should only be called once in an app. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set.
The built-in column master key store providers that are available for the Windows Certificate Store, CNG Store and CSP are pre-registered.
customKeyStoreProviders = new Dictionary();
MySqlClientHSMProvider myProvider = new MySqlClientHSMProvider();
customKeyStoreProviders.Add(@"HSM Provider", myProvider);
SqlConnection.RegisterColumnEncryptionKeyStoreProviders(customKeyStoreProviders);
```
]]>
A null dictionary was provided.
-or-
A string key in the dictionary was null or empty.
-or-
A value in the dictionary was null.
A string key in the dictionary started with "MSSQL_". This prefix is reserved for system providers.
This function was called more than once.
Dictionary of custom column encryption key providersRegisters the encryption key store providers on the instance. If this function has been called, any providers registered using the static methods will be ignored. This function can be called more than once. This does shallow copying of the dictionary so that the app cannot alter the custom provider list once it has been set.
A null dictionary was provided.
-or-
A string key in the dictionary was null or empty.
-or-
A value in the dictionary was null.
A string key in the dictionary started with "MSSQL_". This prefix is reserved for system providers.
Gets or sets the access token for the connection.The access token for the connection.
0 along with AccessToken, you must call after the access token expires to ensure the connection pool doesn't maintain those connections indefinitely.
]]>
The connection ID of the most recent connection attempt, regardless of whether the attempt succeeded or failed.The connection ID of the most recent connection attempt.
works regardless of which version of the server you connect to, but extended events logs and entry on connectivity ring buffer errors will not be present in SQL Server 2008 R2 and earlier.
You can locate the connection ID in the extended events log to see if the failure was on the server if the extended event for logging connection ID is enabled. You can also locate the connection ID in the connection ring buffer ([Connectivity troubleshooting in SQL Server 2008 with the Connectivity Ring Buffer](https://go.microsoft.com/fwlink/?LinkId=207752)) for certain connection errors. If the connection ID is not in the connection ring buffer, you can assume a network error.
]]>
Gets or sets the access token callback for the connection.
The Func that takes a and and returns a .
.
[!code-csharp[SqlConnection_AccessTokenCallback Example#1](~/../sqlclient/doc/samples/SqlConnection_AccessTokenCallback.cs#1)]
]]>
The AccessTokenCallback is combined with other conflicting authentication configurations.
for internal test only
for internal test only
Gets the default wait time (in seconds) before terminating the attempt to execute a command and generating an error. The default is 30 seconds.
The time in seconds to wait for the command to execute. The default is 30 seconds.
Gets or sets the string used to open a SQL Server database.The connection string that includes the source database name, and other parameters needed to establish the initial connection. The default value is an empty string.
is similar to an OLE DB connection string, but is not identical. Unlike OLE DB or ADO, the connection string that is returned is the same as the user-set , minus security information if the Persist Security Info value is set to `false` (default). The .NET Framework Data Provider for SQL Server does not persist or return the password in a connection string unless you set Persist Security Info to `true`.
You can use the property to connect to a database. The following example illustrates a typical connection string.
```
"Persist Security Info=False;Integrated Security=true;Initial Catalog=Northwind;server=(local)"
```
Use the new to construct valid connection strings at run time. For more information, see [Connection String Builders](/sql/connect/ado-net/connection-string-builders).
The property can be set only when the connection is closed. Many of the connection string values have corresponding read-only properties. When the connection string is set, these properties are updated, except when an error is detected. In this case, none of the properties are updated. properties return only those settings that are contained in the .
To connect to a local computer, specify "(local)" for the server. If a server name is not specified, a connection will be attempted to the default instance on the local computer.
Resetting the on a closed connection resets all connection string values (and related properties) including the password. For example, if you set a connection string that includes "Database= AdventureWorks", and then reset the connection string to "Data Source=myserver;Integrated Security=true", the property is no longer set to "AdventureWorks".
The connection string is parsed immediately after being set. If errors in syntax are found when parsing, a runtime exception, such as , is generated. Other errors can be found only when an attempt is made to open the connection.
The basic format of a connection string includes a series of keyword/value pairs separated by semicolons. The equal sign (=) connects each keyword and its value. To include values that contain a semicolon, single-quote character, or double-quote character, the value must be enclosed in double quotation marks. If the value contains both a semicolon and a double-quote character, the value can be enclosed in single quotation marks. The single quotation mark is also useful if the value starts with a double-quote character. Conversely, the double quotation mark can be used if the value starts with a single quotation mark. If the value contains both single-quote and double-quote characters, the quotation mark character used to enclose the value must be doubled every time it occurs within the value.
To include preceding or trailing spaces in the string value, the value must be enclosed in either single quotation marks or double quotation marks. Any leading or trailing spaces around integer, Boolean, or enumerated values are ignored, even if enclosed in quotation marks. However, spaces within a string literal keyword or value are preserved. Single or double quotation marks may be used within a connection string without using delimiters (for example, Data Source= my'Server or Data Source= my"Server), unless a quotation mark character is the first or last character in the value.
Keywords are not case sensitive.
The following table lists the valid names for keyword values within the .
|Keyword|Default|Description|
|-------------|-------------|-----------------|
|Addr|N/A|Synonym of **Data Source**.|
|Address|N/A|Synonym of **Data Source**.|
|App|N/A|Synonym of **Application Name**.|
|Application Intent
-or-
ApplicationIntent|ReadWrite|Declares the application workload type when connecting to a server. Possible values are `ReadOnly` and `ReadWrite`. For example:
`ApplicationIntent=ReadOnly`
For more information about SqlClient support for Always On Availability Groups, see [SqlClient Support for High Availability, Disaster Recovery](/sql/connect/ado-net/sql/sqlclient-support-high-availability-disaster-recovery).|
|Application Name|N/A|The name of the application. If no application name is provided, 'Framework Microsoft SqlClient Data Provider' when running on .NET Framework and 'Core Microsoft SqlClient Data Provider' otherwise.
An application name can be 128 characters or less.|
|AttachDBFilename
-or-
Extended Properties
-or-
Initial File Name|N/A|The name of the primary database file, including the full path name of an attachable database. AttachDBFilename is only supported for primary data files with an .mdf extension.
If the value of the AttachDBFileName key is specified in the connection string, the database is attached and becomes the default database for the connection.
If this key is not specified and if the database was previously attached, the database will not be reattached. The previously attached database will be used as the default database for the connection.
If this key is specified together with the AttachDBFileName key, the value of this key will be used as the alias. However, if the name is already used in another attached database, the connection will fail.
The path may be absolute or relative by using the DataDirectory substitution string. If DataDirectory is used, the database file must exist within a subdirectory of the directory pointed to by the substitution string. **Note:** Remote server, HTTP, and UNC path names are not supported.
The database name must be specified with the keyword 'database' (or one of its aliases) as in the following:
"AttachDbFileName=|DataDirectory|\data\YourDB.mdf;integrated security=true;database=YourDatabase"
An error will be generated if a log file exists in the same directory as the data file and the 'database' keyword is used when attaching the primary data file. In this case, remove the log file. Once the database is attached, a new log file will be automatically generated based on the physical path.|
|Attestation Protocol|NotSpecified|Gets or sets the value of Attestation Protocol.
When no value is specified, secure enclaves are disabled on the connection.
Valid values are:
`AAS`
`HGS`
`None` (Only valid in v3.1 and v4.1+))|
|Authentication|N/A|The authentication method used for [Connecting to SQL Database By Using Azure Active Directory Authentication](https://azure.microsoft.com/documentation/articles/sql-database-aad-authentication/#7-connect-to-your-database-by-using-azure-active-directory-identities).
Valid values are:
`Active Directory Integrated`, `Active Directory Interactive`, `Active Directory Password`, `Active Directory Service Principal`, `Active Directory Device Code Flow`, `Active Directory Managed Identity`, `Active Directory MSI`, `Active Directory Default`, `Sql Password`.
For additional information see [Using Azure Active Directory authentication with SqlClient](https://docs.microsoft.com/sql/connect/ado-net/sql/azure-active-directory-authentication?view=sql-server-ver15).|
|Column Encryption Setting|disabled|Enables or disables [Always Encrypted](/sql/relational-databases/security/encryption/always-encrypted-database-engine) functionality for the connection. Supported values are: `enabled` and `disabled`|
|Command Timeout|30|The default wait time (in seconds) before terminating the attempt to execute a command and generating an error.
Valid values are greater than or equal to 0 and less than or equal to 2147483647.|
|Connect Retry Count
-or-
ConnectRetryCount|1|Controls the number of reconnection attempts after the client identifies an idle connection failure. Valid values are 0 to 255. 0 means do not attempt to reconnect (disable connection resiliency).
Note: Since version 5.x the default value for non Azure endpoints is 1. For Azure SQL endpoints, the default is 2. For Azure SQL serverless or on demand endpoints, the default is 5 to improve connection success for connections to an idle or paused instance.
For additional information about idle connection resiliency, see [.NET SqlConnection parameters for connection retry](https://learn.microsoft.com/azure/azure-sql/database/troubleshoot-common-connectivity-issues?view=azuresql#net-sqlconnection-parameters-for-connection-retry) and [Technical Article - Idle Connection Resiliency](https://go.microsoft.com/fwlink/?LinkId=393996).|
|Connect Retry Interval
-or-
ConnectRetryInterval|10|Specifies the time between each connection retry attempt (`ConnectRetryCount`). Valid values are 1 to 60 seconds (default=10), applied after the first reconnection attempt. When a broken connection is detected, the client immediately attempts to reconnect; this is the first reconnection attempt and only occurs if `ConnectRetryCount` is greater than 0. If the first reconnection attempt fails and `ConnectRetryCount` is greater than 1, the client waits `ConnectRetryInterval` to try the second and subsequent reconnection attempts.
For additional information about idle connection resiliency, see[.NET SqlConnection parameters for connection retry](https://learn.microsoft.com/azure/azure-sql/database/troubleshoot-common-connectivity-issues?view=azuresql#net-sqlconnection-parameters-for-connection-retry) and [Technical Article - Idle Connection Resiliency](https://go.microsoft.com/fwlink/?LinkId=393996).|
|Connect Timeout
-or-
Connection Timeout
-or-
Timeout|15|The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.
Valid values are greater than or equal to 0 and less than or equal to 2147483647.
When opening a connection to a Azure SQL Database, set the connection timeout to 30 seconds.|
|Current Language
-or-
Language|N/A|Sets the language used for database server warning or error messages.
The language name can be 128 characters or less.|
|Data Source
-or-
Server
-or-
Address
-or-
Addr
-or-
Network Address|N/A|The name or network address of the instance of SQL Server to which to connect. The port number can be specified after the server name:
`server=tcp:servername, portnumber`
When specifying a local instance, always use (local). To force a protocol, add one of the following prefixes:
`np:(local), tcp:(local), lpc:(local)`
You can also connect to a LocalDB database as follows:
`server=(localdb)\\myInstance`
For more information about LocalDB, see [SqlClient Support for LocalDB](/sql/connect/ado-net/sql/sqlclient-support-localdb).
**Data Source** must use the TCP format or the Named Pipes format.
TCP format is as follows:
- tcp:\\\
- tcp:\,\
The TCP format must start with the prefix "tcp:" and is followed by the database instance, as specified by a host name and an instance name. This format is not applicable when connecting to Azure SQL Database. TCP is automatically selected for connections to Azure SQL Database when no protocol is specified.
The host name MUST be specified in one of the following ways:
- NetBIOSName
- IPv4Address
- IPv6Address
The instance name is used to resolve to a particular TCP/IP port number on which a database instance is hosted. Alternatively, specifying a TCP/IP port number directly is also allowed. If both instance name and port number are not present, the default database instance is used.
The Named Pipes format is as follows:
- np:\\\\\pipe\\
The Named Pipes format MUST start with the prefix "np:" and is followed by a named pipe name.
The host name MUST be specified in one of the following ways:
- NetBIOSName
- IPv4Address
- IPv6Address
The pipe name is used to identify the database instance to which the .NET application will connect.
If the value of the **Network** key is specified, the prefixes "tcp:" and "np:" should not be specified. **Note:** You can force the use of TCP instead of shared memory, either by prefixing **tcp:** to the server name in the connection string, or by using **localhost**.|
|Enclave Attestation Url|N/A|Gets or sets the enclave attestation URL to be used with enclave based Always Encrypted.|
|Encrypt|'true' in 4.0 and above
'false' in 3.x and below|Recognized values are:
versions 1 - 4: `true`/`yes` and `false`/`no`
versions 5+: `true`/`yes`/`mandatory`, `false`/`no`/`optional` and `strict`. When `true`, TLS encryption is used for all data sent between the client and server if the server has a certificate installed. When `strict`, TDS 8.0 TLS encryption is used and the `TrustServerCertificate` setting is ignored and treated as false. For more information, see [Connection String Syntax](/sql/connect/ado-net/connection-string-syntax).
When `Encrypt` is `mandatory` or `strict` and `TrustServerCertificate` is `false`, the server name (or IP address) in a server's certificate must exactly match the server name (or IP address) specified in the connection string. Otherwise, the connection attempt will fail. |
|Enlist|'true'|`true` indicates that the SQL Server connection pooler automatically enlists the connection in the creation thread's current transaction context.|
|Failover Partner|N/A|The name of the failover partner server where database mirroring is configured.
If the value of this key is "", then **Initial Catalog** must be present, and its value must not be "".
The server name can be 128 characters or less.
If you specify a failover partner but the failover partner server is not configured for database mirroring and the primary server (specified with the Server keyword) is not available, then the connection will fail.
If you specify a failover partner and the primary server is not configured for database mirroring, the connection to the primary server (specified with the Server keyword) will succeed if the primary server is available.|
|Failover Partner SPN
-or-
FailoverPartnerSPN|N/A|The SPN for the failover partner. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN.
(Only available in v5.0+)|
|Host Name In Certificate
-or-
HostNameInCertificate|N/A|The host name to use when validating the server certificate. When not specified, the server name from the Data Source is used for certificate validation.
(Only available in v5.0+)|
|Server Certificate
-or-
ServerCertificate|N/A|The path to a certificate file to match against the SQL Server TLS/SSL certificate. The accepted certificate formats are PEM, DER, and CER. If specified, the SQL Server certificate is checked by verifying if the ServerCertificate provided is an exact match.
(Only available in v5.1+)|
|Initial Catalog
-or-
Database|N/A|The name of the database.
The database name can be 128 characters or less.|
|Integrated Security
-or-
Trusted_Connection|'false'|When `false`, User ID and Password are specified in the connection. When `true`, the current Windows account credentials are used for authentication.
Recognized values are `true`, `false`, `yes`, `no`, and `sspi` (strongly recommended), which is equivalent to `true`.
If User ID and Password are specified and Integrated Security is set to true, the User ID and Password will be ignored and Integrated Security will be used.
is a more secure way to specify credentials for a connection that uses SQL Server Authentication (`Integrated Security=false`).|
|IP Address Preference
-or-
IPAddressPreference|IPv4First|The IP address family preference when establishing TCP connections. If `Transparent Network IP Resolution` (in .NET Framework) or `Multi Subnet Failover` is set to true, this setting has no effect. Supported values include:
`IPAddressPreference=IPv4First`
`IPAddressPreference=IPv6First`
`IPAddressPreference=UsePlatformDefault`|
|Load Balance Timeout
-or-
Connection Lifetime|0|When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by `Connection Lifetime`. This is useful in clustered configurations to force load balancing between a running server and a server just brought online.
A value of zero (0) causes pooled connections to have the maximum connection timeout.|
|Max Pool Size|100|The maximum number of connections that are allowed in the pool.
Valid values are greater than or equal to 1. Values that are less than **Min Pool Size** generate an error.|
|Min Pool Size|0|The minimum number of connections that are allowed in the pool.
Valid values are greater than or equal to 0. Zero (0) in this field means no minimum connections are initially opened.
Values that are greater than **Max Pool Size** generate an error.|
|Multiple Active Result Sets
-or-
MultipleActiveResultSets|false|When `true`, an application can maintain multiple active result sets (MARS). When `false`, an application must process or cancel all result sets from one batch before it can execute any other batch on that connection.
Recognized values are `true` and `false`.
For more information, see [Multiple Active Result Sets (MARS)](/sql/connect/ado-net/sql/multiple-active-result-sets-mars).|
|Multi Subnet Failover
-or-
MultiSubnetFailover|false|Always specify `multiSubnetFailover=True` when connecting to the availability group listener of a SQL Server 2012 (or later) availability group or a SQL Server 2012 (or later) Failover Cluster Instance. `multiSubnetFailover=True` configures SqlClient to provide faster detection of and connection to the (currently) active server. Possible values are `Yes` and `No`, `True` and `False` or `1` and `0`. For example:
`MultiSubnetFailover=True`
The default is `False`. For more information about SqlClient's support for Always On AGs, see [SqlClient Support for High Availability, Disaster Recovery](/sql/connect/ado-net/sql/sqlclient-support-high-availability-disaster-recovery).|
|Network Library
-or-
Network
-or-
Net|N/A|The network library used to establish a connection to an instance of SQL Server. Supported values include:
dbnmpntw (Named Pipes)
dbmsrpcn (Multiprotocol, Windows RPC)
dbmsadsn (Apple Talk)
dbmsgnet (VIA)
dbmslpcn (Shared Memory)
dbmsspxn (IPX/SPX)
dbmssocn (TCP/IP)
Dbmsvinn (Banyan Vines)
The corresponding network DLL must be installed on the system to which you connect. If you do not specify a network and you use a local server (for example, "." or "(local)"), shared memory is used. In this example, the network library is Win32 Winsock TCP/IP (dbmssocn), and 1433 is the port being used.
`Network Library=dbmssocn;Data Source=000.000.000.000,1433;`|
|Packet Size|8000|Size in bytes of the network packets used to communicate with an instance of SQL Server.
The packet size can be greater than or equal to 512 and less than or equal to 32768.|
|Password
-or-
PWD|N/A|The password for the SQL Server account logging on. Not recommended. To maintain a high level of security, we strongly recommend that you use the `Integrated Security` or `Trusted_Connection` keyword instead. is a more secure way to specify credentials for a connection that uses SQL Server Authentication.
The password must be 128 characters or less.|
|Persist Security Info
-or-
PersistSecurityInfo|'false'|When set to `false` or `no` (strongly recommended), security-sensitive information, such as the password or access token, is not returned as part of the connection if the connection is open or has ever been in an open state. This property should only be set to `true` if your application has a specific need to read the password out of an already-opened database connection. The default value of `false` is the more secure setting; using `true` for this property opens your application to security risks such as accidentally logging or tracing the database password.
Resetting the connection string resets all connection string values including the password. Recognized values are `true`, `false`, `yes`, and `no`.|
|Pool Blocking Period
-or-
PoolBlockingPeriod|Auto|Sets the blocking period behavior for a connection pool. See property for details.|
|Pooling|'true'|When the value of this key is set to true, any newly created connection will be added to the pool when closed by the application. In a next attempt to open the same connection, that connection will be drawn from the pool.
Connections are considered the same if they have the same connection string. Different connections have different connection strings.
The value of this key can be "true", "false", "yes", or "no".|
|Replication|'false'|`true` if replication is supported using the connection.|
|Server SPN
-or-
ServerSPN|N/A|The SPN for the data source. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN.
(Only available in v5.0+)|
|Transaction Binding|Implicit Unbind|Controls connection association with an enlisted `System.Transactions` transaction.
Possible values are:
`Transaction Binding=Implicit Unbind;`
`Transaction Binding=Explicit Unbind;`
Implicit Unbind causes the connection to detach from the transaction when it ends. After detaching, additional requests on the connection are performed in autocommit mode. The `System.Transactions.Transaction.Current` property is not checked when executing requests while the transaction is active. After the transaction has ended, additional requests are performed in autocommit mode.
If the system ends the transaction (in the scope of a using block) before the last command completes, it will throw .
Explicit Unbind causes the connection to remain attached to the transaction until the connection is closed or an explicit `SqlConnection.TransactionEnlist(null)` is called. Beginning in .NET Framework 4.0, changes to Implicit Unbind make Explicit Unbind obsolete. An `InvalidOperationException` is thrown if `Transaction.Current` is not the enlisted transaction or if the enlisted transaction is not active.|
|Transparent Network IP Resolution
-or-
TransparentNetworkIPResolution|See description.|When the value of this key is set to `true`, the application is required to retrieve all IP addresses for a particular DNS entry and attempt to connect with the first one in the list. If the connection is not established within 0.5 seconds, the application will try to connect to all others in parallel. When the first answers, the application will establish the connection with the respondent IP address.
If the `MultiSubnetFailover` key is set to `true`, `TransparentNetworkIPResolution` is ignored.
If the `Failover Partner` key is set, `TransparentNetworkIPResolution` is ignored.
The value of this key must be `true`, `false`, `yes`, or `no`.
A value of `yes` is treated the same as a value of `true`.
A value of `no` is treated the same as a value of `false`.
The default values are as follows:
- `false` when:
- Connecting to Azure SQL Database where the data source ends with:
- .database.chinacloudapi.cn
- .database.usgovcloudapi.net
- .database.cloudapi.de
- .database.windows.net
- `Authentication` is 'Active Directory Password' or 'Active Directory Integrated'
- `true` in all other cases.
|
|Trust Server Certificate
-or-
TrustServerCertificate|'false'|When set to `true`, TLS is used to encrypt the channel when bypassing walking the certificate chain to validate trust. If TrustServerCertificate is set to `true` and Encrypt is set to `false`, the channel is not encrypted. Recognized values are `true`, `false`, `yes`, and `no`. For more information, see [Connection String Syntax](/sql/connect/ado-net/connection-string-syntax).|
|Type System Version|N/A|A string value that indicates the type system the application expects. The functionality available to a client application is dependent on the version of SQL Server and the compatibility level of the database. Explicitly setting the type system version that the client application was written for avoids potential problems that could cause an application to break if a different version of SQL Server is used. **Note:** The type system version cannot be set for common language runtime (CLR) code executing in-process in SQL Server. For more information, see [SQL Server Common Language Runtime Integration](/dotnet/framework/data/adonet/sql/sql-server-common-language-runtime-integration).
Possible values are:
`Type System Version=SQL Server 2012;`
`Type System Version=SQL Server 2008;`
`Type System Version=SQL Server 2005;`
`Type System Version=Latest;`
`Type System Version=SQL Server 2012;` specifies that the application will require version 11.0.0.0 of Microsoft.SqlServer.Types.dll. The other `Type System Version` settings will require version 10.0.0.0 of Microsoft.SqlServer.Types.dll.
`Latest` is obsolete and should not be used. `Latest` is equivalent to `Type System Version=SQL Server 2008;`.|
|User ID
-or-
UID
-or-
User|N/A|The SQL Server login account. Not recommended. To maintain a high level of security, we strongly recommend that you use the `Integrated Security` or `Trusted_Connection` keywords instead. is a more secure way to specify credentials for a connection that uses SQL Server Authentication.
The user ID must be 128 characters or less.|
|User Instance|'false'|A value that indicates whether to redirect the connection from the default SQL Server Express instance to a runtime-initiated instance running under the account of the caller.|
|Workstation ID
-or-
WSID|The local computer name|The name of the workstation connecting to SQL Server.
The ID must be 128 characters or less.|
The following list contains the valid names for connection pooling values within the . For more information, see [SQL Server Connection Pooling (ADO.NET)](/sql/connect/ado-net/sql-server-connection-pooling).
- Connection Lifetime (or Load Balance Timeout)
- Enlist
- Max Pool Size
- Min Pool Size
- Pooling
When you are setting keyword or connection pooling values that require a Boolean value, you can use 'yes' instead of 'true', and 'no' instead of 'false'. Integer values are represented as strings.
> [!NOTE]
> The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. Therefore, it does not support the use of an ODBC data source name (DSN) when connecting to SQL Server because it does not add an ODBC layer.
> [!NOTE]
> Universal data link (UDL) files are not supported for the .NET Framework Data Provider for SQL Server.
> [!CAUTION]
> In this release, the application should use caution when constructing a connection string based on user input (for example when retrieving user ID and password information from a dialog box, and appending it to the connection string). The application should make sure that a user cannot embed additional connection string parameters in these values (for example, entering a password as "validpassword;database=somedb" in an attempt to attach to a different database). If you need to construct connection strings based on user input, use the new , which validates the connection string and helps to eliminate this problem. See [Connection String Builders](/sql/connect/ado-net/connection-string-builders) for more information.
## Examples
The following example creates a and sets the property before opening the connection.
[!code-csharp[SqlConnection_ConnectionString Example#1](~/../sqlclient/doc/samples/SqlConnection_ConnectionString.cs#1)]
]]>
An invalid connection string argument has been supplied, or a required connection string argument has not been supplied.
Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.The time (in seconds) to wait for a connection to open. The default value is 15 seconds.
because an attempt to connect waits indefinitely.
## Examples
The following example creates a and sets the `Connection Timeout` to 30 seconds in the connection string. The code opens the connection and displays the property in the console window.
[!code-csharp[SqlConnection_ConnectionTimeout Example#1](~/../sqlclient/doc/samples/SqlConnection_ConnectionTimeout.cs#1)]
]]>
The value set is less than 0.
Gets or sets the object for this connection.The object for this connection.
object with .
The default value of is null.
An exception will be raised:
- If is set on an open connection.
- If is set when `Integrated Security = true`.
- If is set when the connection string uses `Password`.
- If is set when the connection string uses `UserID`.
]]>
Gets the name of the current database or the database to be used after a connection is opened.The name of the current database or the name of the database to be used after a connection is opened. The default value is an empty string.
property updates dynamically. If you change the current database using a Transact-SQL statement or the method, an informational message is sent and the property is updated automatically.
## Examples
The following example creates a and displays some of its read-only properties.
[!code-csharp[SqlConnection_Database Example#1](~/../sqlclient/doc/samples/SqlConnection_Database.cs#1)]
]]>
Gets the name of the instance of SQL Server to which to connect.The name of the instance of SQL Server to which to connect. The default value is an empty string.
and displays some of its read-only properties.
[!code-csharp[SqlConnection_DataSource Example#1](~/../sqlclient/doc/samples/SqlConnection_DataSource.cs#1)]
]]>
Gets or sets the property.
if the property has been set; otherwise .
to `true`, errors that were previously treated as exceptions are now handled as events. All events fire immediately and are handled by the event handler. If is is set to `false`, then events are handled at the end of the procedure.
> [!NOTE]
> An error with a severity level of 17 or above that causes the server to stop processing the command needs to be handled as an exception. In this case, an exception is thrown regardless of how the error is handled in the event.
For more information on working with events, see [Connection Events](/sql/connect/ado-net/connection-events). For more information on errors generated by the SQL Server engine, see [Database Engine Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors).
]]>
Gets the size (in bytes) of network packets used to communicate with an instance of SQL Server.The size (in bytes) of network packets. The default value is 8000.
), which is sufficient for most data transfer operations. For most applications, the default packet size is best.
may be a value in the range of 512 and 32767 bytes. An exception is generated if the value is outside this range.
Setting the default value to a number greater than 8000 will cause the packets to use the MultiPage allocator on the instance of SQL Server instead of the much more efficient SinglePage allocator, reducing the overall scalability of the SQL Server. For more information on how SQL Server uses memory, see [Memory Management Architecture Guide](/sql/relational-databases/memory-management-architecture-guide).
## Examples
The following example creates a , including setting the `Packet Size` to 512 in the connection string. It displays the and properties in the console window.
[!code-csharp[SqlConnection_PacketSize Example#1](~/../sqlclient/doc/samples/SqlConnection_PacketSize.cs#1)]
]]>
Gets a string that contains the version of the instance of SQL Server to which the client is connected.The version of the instance of SQL Server.
was called while the returned Task was not completed and the connection was not opened after a call to .
## Examples
The following example creates a and displays the property.
[!code-csharp[SqlConnection_ServerVersion Example#1](~/../sqlclient/doc/samples/SqlConnection_ServerVersion.cs#1)]
]]>
The connection is closed.
was called while the returned Task was not completed and the connection was not opened after a call to .
Gets the server process Id (SPID) of the active connection.The server process Id (SPID) of the active connection.Returns 0 if the connection is inactive on the client side.
Indicates the state of the during the most recent network operation performed on the connection.An enumeration.
enumeration indicating the state of the . Closing and reopening the connection will refresh the value of .
]]>
When set to , enables statistics gathering for the current connection.Returns if statistics gathering is enabled; otherwise . is the default.
Gets a string that identifies the database client.A string that identifies the database client. If not specified, the name of the client computer. If neither is specified, the value is an empty string.
property corresponds to the `Workstation ID` connection string property.
## Examples
The following example creates a and displays the property.
[!code-csharp[SqlConnection_WorkstationId Example#1](~/../sqlclient/doc/samples/SqlConnection_WorkstationId.cs#1)]
]]>
Occurs when SQL Server returns a warning or informational message.
delegate to listen to this event.
The event occurs when a message with a severity of 10 or less is returned by SQL Server. Messages that have a severity between 11 and 20 raise an error and messages that have a severity over 20 causes the connection to close. For more information on SQL Server error levels, see [Database Engine Error Severities](/sql/relational-databases/errors-events/database-engine-error-severities).
For more information and an example, see [Connection Events](/sql/connect/ado-net/connection-events).
]]>
To be added.To be added.To be added.To be added.
Starts a database transaction.An object representing the new transaction.
or method. To make sure that the .NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
> [!NOTE]
> If you do not specify an isolation level, the default isolation level is used. To specify an isolation level with the method, use the overload that takes the `iso` parameter (). The isolation level set for a transaction persists after the transaction is completed and until the connection is closed or disposed. Setting the isolation level to **Snapshot** in a database where the snapshot isolation level is not enabled does not throw an exception. The transaction will complete using the default isolation level.
> [!CAUTION]
> If a transaction is started and a level 16 or higher error occurs on the server, the transaction will not be rolled back until the method is invoked. No exception is thrown on **ExecuteReader**.
> [!CAUTION]
> When your query returns a large amount of data and calls `BeginTransaction`, a is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.
For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql).
## Examples
The following example creates a and a . It also demonstrates how to use the , a , and methods.
[!code-csharp[SqlConnection_BeginTransaction Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction.cs#1)]
]]>
Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).Parallel transactions are not supported.
The isolation level under which the transaction should run.Starts a database transaction with the specified isolation level.An object representing the new transaction.
or method. To make sure that the .NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
> [!NOTE]
> After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the SQL Server default). This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. To reset the isolation level to the default (READ COMMITTED), execute the Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call followed immediately by . For more information on SQL Server isolation levels, see [Transaction Isolation Levels](/sql/t-sql/language-elements/transaction-isolation-levels).
For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql).
> [!CAUTION]
> When your query returns a large amount of data and calls `BeginTransaction`, a is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.
## Examples
The following example creates a and a . It also demonstrates how to use the , a , and methods.
[!code-csharp[SqlConnection_BeginTransaction1 Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction1.cs#1)]
]]>
Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).Parallel transactions are not supported.
The isolation level under which the transaction should run.The name of the transaction.Starts a database transaction with the specified isolation level and transaction name.An object representing the new transaction.
and in the `savePoint` parameter of the method.
You must explicitly commit or roll back the transaction using the or method. To make sure that the SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
> [!NOTE]
> After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the SQL Server default). This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. To reset the isolation level to the default (READ COMMITTED), execute the Transact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call followed immediately by . For more information on SQL Server isolation levels, see [Transaction Isolation Levels](/sql/t-sql/language-elements/transaction-isolation-levels).
For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql).
> [!CAUTION]
> When your query returns a large amount of data and calls `BeginTransaction`, a is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.
## Examples
The following example creates a and a . It also demonstrates how to use the , a , and methods.
[!code-csharp[SqlConnection_BeginTransaction3 Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction3.cs#1)]
]]>
Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).Parallel transactions are not supported.
The name of the transaction.Starts a database transaction with the specified transaction name.An object representing the new transaction.
and in the `savePoint` parameter of the method.
You must explicitly commit or roll back the transaction using the or method. To make sure that the .NET Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.
For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql).
> [!CAUTION]
> When your query returns a large amount of data and calls `BeginTransaction`, a is thrown because SQL Server does not allow parallel transactions when using MARS. To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.
## Examples
The following example creates a and a . It also demonstrates how to use the , a , and methods.
[!code-csharp[SqlConnection_BeginTransaction2 Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction2.cs#1)]
]]>
Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).Parallel transactions are not supported.
The name of the database to use instead of the current database.Changes the current database for an open .
and displays some of its read-only properties.
[!code-csharp[SqlConnection_Database Example#1](~/../sqlclient/doc/samples/SqlConnection_Database.cs#1)]
]]>
The database name is not valid.The connection is not open.Cannot change the database.
The connection string that contains enough information to connect to a server. The connection string should not use any of the following connection string keywords: , , or ; or .A object.The new password. must be read only. The password must also comply with any password security policy set on the server (for example, minimum length and requirements for specific characters).Changes the SQL Server password for the user indicated in the object.To be added.
The connection string contains any combination of , , or .
-or-
is greater than 128 characters.
-or-
is not read only.
-or-
is an empty string.One of the parameters (, , or ) is null.
The connection string that contains enough information to connect to the server that you want. The connection string must contain the user ID and the current password.The new password to set. This password must comply with any password security policy set on the server, including minimum length, requirements for specific characters, and so on.Changes the SQL Server password for the user indicated in the connection string to the supplied new password.
method changes the SQL Server password for the user indicated in the supplied `connectionString` parameter to the value supplied in the `newPassword` parameter. If the connection string includes the option for integrated security (that is, "Integrated Security=True" or the equivalent), an exception is thrown.
To determine that the password has expired, calling the method raises a . In order to indicate that the password that is contained within the connection string must be reset, the property for the exception contains the status value 18487 or 18488. The first value (18487) indicates that the password has expired and the second (18488) indicates that the password must be reset before logging in.
This method opens its own connection to the server, requests the password change, and closes the connection as soon as it has completed. This connection is not retrieved from, nor returned to, the SQL Server connection pool.
## Examples
The following is a simple example of changing a password:
```csharp
class Program {
static void Main(string[] args) {
Microsoft.Data.SqlClient.SqlConnection.ChangePassword(
"Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password",
"new_password");
}
}
```
```vb
Module Module1
Sub Main()
Microsoft.Data.SqlClient.SqlConnection.ChangePassword(
"Data Source=a_server;Initial Catalog=a_database;UID=user;PWD=old_password",
"new_password")
End Sub
End Module
```
The following console application demonstrates the issues involved in changing a user's password because the current password has expired.
[!code-csharp[SqlConnection_ConnectionString1#1](~/../sqlclient/doc/samples/SqlConnection_ConnectionString1.cs#1)]
]]>
The connection string includes the option to use integrated security.
Or
The exceeds 128 characters.Either the or the parameter is null.
Empties the connection pool.
resets (or empties) the connection pool. If there are connections in use at the time of the call, they are marked appropriately and will be discarded (instead of being returned to the pool) when is called on them.
]]>
The to be cleared from the pool.Empties the connection pool associated with the specified connection.
clears the connection pool that is associated with the `connection`. If additional connections associated with `connection` are in use at the time of the call, they are marked appropriately and are discarded (instead of being returned to the pool) when is called on them.
]]>
Closes the connection to the database. This is the preferred method of closing any open connection.
method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled.
> [!NOTE]
> Pending transactions started using Transact-SQL or are automatically rolled back when the connection is reset if connection pooling is enabled. If connection pooling is off, the transaction is rolled back after `SqlConnection.Close` is called. Transactions started through are controlled through the `System.Transactions` infrastructure, and are not affected by `SqlConnection.Close`.
An application can call more than one time. No exception is generated.
If the goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling `Close` or `Dispose`. `Close` and `Dispose` are functionally equivalent. If the connection pooling value `Pooling` is set to `true` or `yes`, the underlying connection is returned back to the connection pool. On the other hand, if `Pooling` is set to `false` or `no`, the underlying connection to the server is closed.
> [!NOTE]
> Login and logout events will not be raised on the server when a connection is fetched from or returned to the connection pool, because the connection is not actually closed when it is returned to the connection pool. For more information, see [SQL Server Connection Pooling (ADO.NET)](/sql/connect/ado-net/sql-server-connection-pooling).
> [!CAUTION]
> Do not call `Close` or `Dispose` on a Connection, a DataReader, or any other managed object in the `Finalize` method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a `Finalize` method in your class definition. For more information, see [Garbage Collection](/dotnet/standard/garbage-collection/).
## Examples
The following example creates a , opens it, displays some of its properties. The connection is automatically closed at the end of the `using` block.
[!code-csharp[SqlConnection_Open Example#1](~/../sqlclient/doc/samples/SqlConnection_Open.cs#1)]
]]>
The connection-level error that occurred while opening the connection.
Creates and returns a object associated with the .A object.
To be added.To be added.To be added.
Returns schema information for the data source of this . For more information about scheme, see [SQL Server Schema Collections](/sql/connect/ado-net/sql-server-schema-collections).A that contains schema information.To be added.
Specifies the name of the schema to return.Returns schema information for the data source of this using the specified string for the schema name.A that contains schema information.
is specified as null.
Specifies the name of the schema to return.A set of restriction values for the requested schema.Returns schema information for the data source of this using the specified string for the schema name and the specified string array for the restriction values.A that contains schema information.
, see .
]]>
is specified as null.
Opens a database connection with the property settings specified by the .
draws an open connection from the connection pool if one is available. Otherwise, it establishes a new connection to an instance of SQL Server.
> [!NOTE]
> If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling .
> [!NOTE]
> If you specify a port number other than 1433 when you are trying to connect to an instance of SQL Server and using a protocol other than TCP/IP, the method fails. To specify a port number other than 1433, include "server=machinename,port number" in the connection string, and use the TCP/IP protocol.
> [!NOTE]
> The .NET Framework Data Provider for SQL Server requires the Security permission with "Allows calls to unmanaged assemblies" enabled ( with set to `UnmanagedCode`) to open a with SQL Debugging enabled.
## Examples
The following example creates a , opens it, and displays some of its properties. The connection is automatically closed at the end of the `using` block.
[!code-csharp[SqlConnection_Open Example#1](~/../sqlclient/doc/samples/SqlConnection_Open.cs#1)]
]]>
Cannot open a connection without specifying a data source or server.
or
The connection is already open.A connection-level error occurred while opening the connection. If the property contains the value 18487 or 18488, this indicates that the specified password has expired or must be reset. See the method for more information.
The tag in the app.config file has invalid or unknown elements.There are two entries with the same name in the section.
Options to override default connection open behavior.
Opens a database connection with the property settings specified by the .
draws an open connection from the connection pool if one is available. Otherwise, it establishes a new connection to an instance of SQL Server. If overrides are specified, the first open attempt will apply the specified overrides to the open action.
> [!NOTE]
> If the goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling .
> [!NOTE]
> If you specify a port number other than 1433 when you are trying to connect to an instance of SQL Server and using a protocol other than TCP/IP, the method fails. To specify a port number other than 1433, include "server=machinename,port number" in the connection string, and use the TCP/IP protocol.
> [!NOTE]
> The .NET Framework Data Provider for SQL Server requires the Security permission with "Allows calls to unmanaged assemblies" enabled ( with set to `UnmanagedCode`) to open a with SQL Debugging enabled.
## Examples
The following example creates a , opens it, and displays some of its properties. The connection is automatically closed at the end of the `using` block.
[!code-csharp[SqlConnection_Open Example#1](~/../sqlclient/doc/samples/SqlConnection_Open.cs#1)]
]]>
Cannot open a connection without specifying a data source or server.
or
The connection is already open.
A connection-level error occurred while opening the connection. If the property contains the value 18487 or 18488, this indicates that the specified password has expired or must be reset. See the method for more information.
The tag in the app.config file has invalid or unknown elements.There are two entries with the same name in the section.
The cancellation instruction.An asynchronous version of , which opens a database connection with the property settings specified by the . The cancellation token can be used to request that the operation be abandoned before the connection timeout elapses. Exceptions will be propagated via the returned Task. If the connection timeout time elapses without successfully connecting, the returned Task will be marked as faulted with an Exception. The implementation returns a Task without blocking the calling thread for both pooled and non-pooled connections.A task representing the asynchronous operation.
, must return until the returned is completed. Then, if the connection was successful, must return . If the connection fails, must return .
A call to will attempt to cancel or close the corresponding call.
For more information about asynchronous programming in the .NET Framework Data Provider for SQL Server, see [Asynchronous Programming](/sql/connect/ado-net/asynchronous-programming).
]]>
Calling more than once for the same instance before task completion.
A connection was not available from the connection pool before the connection time out elapsed.Any error returned by SQL Server that occurred while opening the connection.
If statistics gathering is enabled, all values are reset to zero.
Returns a name value pair collection of statistics at the point in time the method is called.Returns a reference of type of items.
Returns a name value pair collection of internal properties at the point in time the method is called.Returns a reference of type of (string, object) items.
Gets or sets a value that specifies the
object bound to this command.
When set to null (default), the default non-retriable provider will be applied.
type.
2. Create a by using one of the following static methods of the class:
-
-
-
-
3. Assign the object to the `RetryLogicProvider` property.
> [!NOTE]
> Detecting retriable exceptions is a vital part of the retry pattern. Before applying retry logic, it is important to investigate exceptions and choose a retry provider that best fits your scenario. First, log your exceptions and find transient faults.
> [!NOTE]
> The connection **timeout** restarts for each execution of a connection open. There is no timing overlap between these two actions.
> [!NOTE]
> The default retry logic provider is not enabled unless it is configured in an application configuration file. For more information, see [Configurable retry logic and configuration file](/sql/connect/ado-net/configurable-retry-logic-config-file-sqlclient).
## Example
The following sample tries to open a connection to an invalid database to simulate a condition that the database service is temporarily unavailable . You should manually create the database while the tries to establish the connection.
[!code-csharp[SqlConfigurableRetryLogic_OpenConnection#1](~/../sqlclient/doc/samples/SqlConfigurableRetryLogic_OpenConnection.cs#1)]
]]>
To be added.To be added.To be added.
Note that these settings cannot be used to bypass encryption and gain access to plaintext data. For details, see Always Encrypted (Database Engine).To be added.
Specifies the connection does not use Always Encrypted. Should be used if no queries sent over the connection access encrypted columns.
Enables Always Encrypted functionality for the connection. Query parameters that correspond to encrypted columns will be transparently encrypted and query results from encrypted columns will be transparently decrypted.
Specifies a value for Overrides.
No overrides.0
Disable transient fault handling during the initial SqlConnection Open attempt.1
Provides a simple way to create and manage the contents of connection strings used by the class.
class to build and modify connection strings. The class also makes it easy to manage connection strings stored in an application configuration file.
The performs checks for valid key/value pairs. Therefore, you cannot use this class to create invalid connection strings; trying to add invalid pairs will throw an exception. The class maintains a fixed collection of synonyms and can translate from a synonym to the corresponding well-known key name.
For example, when you use the **Item** property to retrieve a value, you can specify a string that contains any synonym for the key you need. For example, you can specify "Network Address", "addr", or any other acceptable synonym for this key within a connection string when you use any member that requires a string that contains the key name, such as the **Item** property or the method. See the property for a full list of acceptable synonyms.
The **Item** property handles tries to insert malicious entries. For example, the following code, using the default Item property (the indexer, in C#) correctly escapes the nested key/value pair:
```vb
Dim builder As New Microsoft.Data.SqlClient.SqlConnectionStringBuilder
builder("Data Source") = "(local)"
builder("Integrated Security") = True
builder("Initial Catalog") = "AdventureWorks;NewValue=Bad"
Console.WriteLine(builder.ConnectionString)
```
```csharp
Microsoft.Data.SqlClient.SqlConnectionStringBuilder builder =
new Microsoft.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["Integrated Security"] = true;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);
```
The result is the following connection string that handles the invalid value in a safe manner:
```
Source=(local);Initial Catalog="AdventureWorks;NewValue=Bad";
Integrated Security=True
```
## Examples
The following console application builds connection strings for a SQL Server database. The code uses a class to create the connection string, and then passes the property of the instance to the constructor of the connection class. The example also parses an existing connection string and demonstrates various ways of manipulating the connection string's contents.
> [!NOTE]
> This example includes a password to demonstrate how works with connection strings. In your applications, we recommend that you use Windows Authentication. If you must use a password, do not include a hard-coded password in your application.
[!code-csharp[SqlConnectionStringBuilder#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder.cs#1)]
]]>
Initializes a new instance of the class.To be added.
The basis for the object's internal connection information. Parsed into name/value pairs. Invalid key names raise .Initializes a new instance of the class. The provided connection string provides the data for the instance's internal connection information.
class provides a fixed internal collection of key/value pairs. Even if you supply only a small subset of the possible connection string values in the constructor, the object always provides default values for each key/value pair. When the `ConnectionString` property of the object is retrieved, the string contains only key/value pairs in which the value is not the default value for the item.
## Examples
The following example supplies a simple SQL Server connection string in the object's constructor, and then iterates through all the key/value pairs within the object. Note that the collection provides default values for each item. Also note that the class converts synonyms for the well-known keys so that they are consistent with the well-known names.
> [!NOTE]
> This example includes a password to demonstrate how works with connection strings. In your applications, we recommend that you use Windows Authentication. If you must use a password, do not include a hard-coded password in your application.
[!code-csharp[SqlConnectionStringBuilder3#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder3.cs#1)]
]]>
Invalid key name within the connection string.Invalid value within the connection string (specifically, when a Boolean or numeric value was expected but not supplied).The supplied is not valid.
Declares the application workload type when connecting to a database in an SQL Server Availability Group. You can set the value of this property with . For more information about SqlClient support for Always On Availability Groups, see [SqlClient Support for High Availability, Disaster Recovery](/sql/connect/ado-net/sql/sqlclient-support-high-availability-disaster-recovery).Returns the current value of the property.
Overview of the SqlClient driver
Gets or sets the name of the application associated with the connection string.The name of the application. If no name has been supplied, "Framework Microsoft SqlClient Data Provider" when running on .NET Framework and "Core Microsoft SqlClient Data Provider" otherwise.
and assigns a connection string in the object's constructor. The code displays the parsed and recreated version of the connection string, and then modifies the property of the object. Finally, the code displays the new connection string, including the new key/value pair.
[!code-csharp[SqlConnectionStringBuilder.ApplicationName#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_ApplicationName.cs#1)]
The sample displays the following text in the console window:
```
Original: Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True
ApplicationName="Core Microsoft SqlClient Data Provider"
Modified: Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True;Application Name="My Application"
```
]]>
To set the value to null, use .
Gets or sets a string that contains the name of the primary data file. This includes the full path name of an attachable database.The value of the property, or if no value has been supplied.
instance, and sets the `AttachDBFilename` property in order to specify the name of an attached data file.
[!code-csharp[DataWorks SqlConnectionStringBuilder_AttachDBFilename#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_AttachDBFilename.cs#1)]
]]>
To set the value to null, use .Working with Connection StringsOverview of the SqlClient driver
Gets or sets the authentication method used for [Connecting to SQL Database By Using Azure Active Directory Authentication](https://azure.microsoft.com/documentation/articles/sql-database-aad-authentication/#7-connect-to-your-database-by-using-azure-active-directory-identities).The authentication method of the connection string.
Gets or sets the column encryption settings for the connection string builder.The column encryption settings for the connection string builder.This property enables or disables [Always Encrypted](/sql/relational-databases/security/encryption/always-encrypted-database-engine) functionality for the connection.
The default wait time (in seconds) before terminating the attempt to execute a command and generating an error. The default is 30 seconds.
The time in seconds to wait for the command to execute. The default is 30 seconds.
connection string.
Valid values are greater than or equal to 0 and less than or equal to 2147483647.
]]>
The value set is less than 0.
The number of reconnections attempted after identifying that there was an idle connection failure. This must be an integer between 0 and 255. The default value for non Azure endpoints is 1. For Azure SQL endpoints, the default is 2. Starting in version 5.x, for Azure SQL serverless or on demand endpoints, the default is 5 to improve connection success for connections to an idle or paused instance. Set to 0 to disable reconnecting on idle connection failures. An will be thrown if set to a value outside of the allowed range.The number of reconnections attempted after identifying that there was an idle connection failure.
connection string.
> [!NOTE]
> Since version 5.x the default value for none Azure endpoints is 1 and for Azure SQL and Azure Synapse has increased to 2 and 5 to imporve the recovery against on high demand Azure endpoints. It should be detected first, and Synapse could be detected as a regular Azure SQL DB endpoint.
]]>
Amount of time (in seconds) between each reconnection attempt after identifying that there was an idle connection failure. This must be an integer between 1 and 60. The default is 10 seconds.Amount of time (in seconds) between each reconnection attempt after identifying that there was an idle connection failure.Value is outside of the allowed range.
connection string.
This value is applied after the first reconnection attempt. When a broken connection is detected, the client immediately attempts to reconnect; this is the first reconnection attempt and only occurs if `ConnectRetryCount` is greater than 0. If the first reconnection attempt fails and `ConnectRetryCount` is greater than 1, the client waits `ConnectRetryInterval` to try the second and subsequent reconnection attempts.
]]>
Gets or sets the length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.The value of the property, or 15 seconds if no value has been supplied.
property, and then displays the new connection string.
[!code-csharp[SqlConnectionStringBuilder_ConnectTimeout#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_ConnectTimeout.cs#1)]
]]>
Gets or sets the language used for database server warning or error messages..The value of the property, or if no value has been supplied.
To set the value to null, use .
Gets or sets the name or network address of the instance of SQL Server to connect to.The value of the property, or if none has been supplied.
\\
- tcp:\,\
The TCP format must start with the prefix "tcp:" and is followed by the database instance, as specified by a host name and an instance name. This format is not applicable when connecting to Azure SQL Database. TCP is automatically selected for connections to Azure SQL Database when no protocol is specified.
The host name MUST be specified in one of the following ways:
- NetBIOSName
- IPv4Address
- IPv6Address
The instance name is used to resolve to a particular TCP/IP port number on which a database instance is hosted. Alternatively, specifying a TCP/IP port number directly is also allowed. If both instance name and port number are not present, the default database instance is used.
The Named Pipes format is as follows:
- np:\\\\\pipe\\
The Named Pipes format MUST start with the prefix "np:" and is followed by a named pipe name.
The host name MUST be specified in one of the following ways:
- NetBIOSName
- IPv4Address
- IPv6Address
The pipe name is used to identify the database instance to which the .NET application will connect.
If the value of the **Network** key is specified, the prefixes "tcp:" and "np:" should not be specified. **Note:** You can force the use of TCP instead of shared memory, either by prefixing **tcp:** to the server name in the connection string, or by using **localhost**.
## Examples
The following example demonstrates that the class converts synonyms for the "Data Source" connection string key into the well-known key:
[!code-csharp[SqlConnectionStringBuilder_DataSource#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_DataSource.cs#1)]
]]>
To set the value to null, use .
Gets or sets the value of Attestation Protocol.The attestation protocol.
Gets or sets the enclave attestation URL to be used with enclave based Always Encrypted.The enclave attestation URL.
Gets or sets the IP address family preference when establishing TCP connections.Returns the IP address preference.
Gets or sets a value since version 5.0 or a value for the earlier versions that indicates whether TLS encryption is required for all data sent between the client and server.The value of the property.
, or `true`, the server name (or IP address) in a server's TLS certificate must exactly match the server name (or IP address) specified in the connection string. Otherwise, the connection attempt will fail. For information about support for certificates whose subject starts with a wildcard character (*), see [Enable encrypted connections to the Database Engine](/sql/database-engine/configure-windows/enable-encrypted-connections-to-the-database-engine#certificate-requirements).
> [!NOTE]
> Starting from **version 4.0**, the default value of the property `Encrypt` is set to `true` while it is `false` for earlier versions.
> [!NOTE]
> Starting from **version 5.0**, the data type is updated to , and the default value of the `Encrypt` property is set to .
]]>
Working with Connection StringsOverview of the SqlClient driver
Gets or sets the host name to use when validating the server certificate for the connection. When not specified, the server name from the `Data Source` is used for certificate validation. (Only available in v5.0+)
The value of the property, or if none has been supplied.
[!NOTE]
> This property only applies when using `Encrypt` in or mode, otherwise it is ignored.
]]>
Gets or sets the path to a certificate file to match against the SQL Server TLS/SSL certificate for the connection. The accepted certificate formats are PEM, DER, and CER. If specified, the SQL Server certificate is checked by verifying if the `ServerCertificate` provided is an exact match. (Only available in v5.1+)
The value of the property, or if none has been supplied.
[!NOTE]
> This property only applies when using `Encrypt` in or mode, otherwise it is ignored.
]]>
Gets or sets a Boolean value that indicates whether the SQL Server connection pooler automatically enlists the connection in the creation thread's current transaction context.The value of the property, or if none has been supplied.
Gets or sets the name or address of the partner server to connect to if the primary server is down.The value of the property, or if none has been supplied.To set the value to null, use .
Gets or sets the service principal name (SPN) of the failover partner for the connection.
The value of the property, or if none has been supplied.
[!NOTE]
> This property only applies when using Integrated Security mode, otherwise it is ignored.
]]>
Gets or sets the name of the database associated with the connection.The value of the property, or if none has been supplied.
class to add the name of the database to the connection string. The code displays the contents of the property, just to verify that the class was able to convert from the synonym ("Database") to the appropriate property value.
[!code-csharp[SqlConnectionStringBuilder_InitialCatalog#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_InitialCatalog.cs#1)]
]]>
To set the value to null, use .
Gets or sets a Boolean value that indicates whether User ID and Password are specified in the connection (when ) or whether the current Windows account credentials are used for authentication (when ).The value of the property, or if none has been supplied.
is a more secure way to specify credentials for a connection that uses SQL Server Authentication (`Integrated Security=false`).
## Examples
The following example converts an existing connection string from using SQL Server Authentication to using integrated security. The example does its work by removing the user name and password from the connection string and then setting the property of the object.
> [!NOTE]
> This example includes a password to demonstrate how works with connection strings. In your applications, we recommend that you use Windows Authentication. If you must use a password, do not include a hard-coded password in your application.
[!code-csharp[SqlConnectionStringBuilder_IntegratedSecurity#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_IntegratedSecurity.cs#1)]
]]>
Gets a value that indicates whether the has a fixed size.
in every case, because the supplies a fixed-size collection of key/value pairs.To be added.Working with Connection StringsOverview of the SqlClient driver
The key of the item to get or set.Gets or sets the value associated with the specified key. In C#, this property is the indexer.The value associated with the specified key.
contains a fixed-size dictionary, trying to add a key that does not exist within the dictionary throws a .
## Examples
The following code, in a console application, creates a new and adds key/value pairs to its connection string, using the property.
[!code-csharp[SqlConnectionStringBuilder2#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder2.cs#1)]
]]>
is a null reference ( in Visual Basic).Tried to add a key that does not exist within the available keys.Invalid value within the connection string (specifically, a Boolean or numeric value was expected but not supplied).
Gets an that contains the keys in the .An that contains the keys in the .
is unspecified, but it is the same order as the associated values in the returned by the property.
## Examples
The following console application example creates a new . The code loops through the returned by the property displaying the key/value pairs.
[!code-csharp[SqlConnectionStringBuilder_Keys#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_Keys.cs#1)]
]]>
Gets or sets the minimum time, in seconds, for the connection to live in the connection pool before being destroyed.The value of the property, or 0 if none has been supplied.
Gets or sets the maximum number of connections allowed in the connection pool for this specific connection string.The value of the property, or 100 if none has been supplied.
Gets or sets the minimum number of connections allowed in the connection pool for this specific connection string.The value of the property, or 0 if none has been supplied.
When true, an application can maintain multiple active result sets (MARS). When false, an application must process or cancel all result sets from one batch before it can execute any other batch on that connection. For more information, see [Multiple Active Result Sets (MARS)](https://msdn.microsoft.com//library/cfa084cz.aspx).The value of the property, or if none has been supplied.
If your application is connecting to an AlwaysOn availability group (AG) on different subnets, setting MultiSubnetFailover=true provides faster detection of and connection to the (currently) active server. For more information about SqlClient support for Always On Availability Groups, see [SqlClient Support for High Availability, Disaster Recovery](/sql/connect/ado-net/sql/sqlclient-support-high-availability-disaster-recovery).Returns indicating the current value of the property.
Gets or sets the size in bytes of the network packets used to communicate with an instance of SQL Server.The value of the property, or 8000 if none has been supplied.
Gets or sets the password for the SQL Server account.The value of the property, or if none has been supplied.
is a more secure way to specify credentials for a connection that uses SQL Server Authentication.
If has not been set and you retrieve the value, the return value is . To reset the password for the connection string, pass null to the Item property.
The password must be 128 characters or less.
## Examples
The following example shows how to set .
[!code-csharp[SqlConnectionStringBuilder_Password#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_Password.cs#1)]
]]>
The password was incorrectly set to null. See code sample below.
Gets or sets a Boolean value indicating if security-sensitive information, such as the password or access token, should be returned as part of the connection string on a connection created with this after that connection has ever been in an open state. This property should only be set to if your application has a specific need to read the password out of an already-opened database connection. The default value of is the more secure setting; using for this property opens your application to security risks such as accidentally logging or tracing the database password.The value of the property, or if none has been supplied.
The blocking period behavior for a connection pool.The available blocking period settings.
enumeration for available settings.
]]>
Gets or sets a Boolean value that indicates whether the connection will be pooled or explicitly opened every time that the connection is requested.The value of the property, or if none has been supplied.
Gets or sets a Boolean value that indicates whether replication is supported using the connection.The value of the property, or false if none has been supplied.
Gets or sets the service principal name (SPN) of the data source.
The value of the property, or if none has been supplied.
[!NOTE]
> This property only applies when using Integrated Security mode, otherwise it is ignored.
]]>
Gets or sets a string value that indicates how the connection maintains its association with an enlisted transaction.The value of the property, or `Implicit Unbind` if none has been supplied.
control how a binds to an enlisted .
The following table shows the possible values for the property:
|Value|Description|
|-----------|-----------------|
|Implicit Unbind|The default. Causes the connection to detach from the transaction when it ends. After detaching, additional requests on the connection are performed in autocommit mode. The property is not checked when executing requests while the transaction is active. After the transaction has ended, additional requests are performed in autocommit mode.|
|Explicit Unbind|Causes the connection to remain attached to the transaction until the connection is closed or until is called with a `null` (`Nothing` in Visual Basic) value. An is thrown if is not the enlisted transaction or if the enlisted transaction is not active. This behavior enforces the strict scoping rules required for support.|
]]>
Gets or sets a value that indicates whether the channel will be encrypted while bypassing walking the certificate chain to validate trust.A boolean. The default is `false`.
Gets or sets a string value that indicates the type system the application expects.The following table shows the possible values for the property:
Value
Description
- SQL Server 2005
Uses the SQL Server 2005 type system. No conversions are made for the current version of ADO.NET.
- SQL Server 2008
Uses the SQL Server 2008 type system.
- Latest
Use the latest version than this client-server pair can handle. This will automatically move forward as the client and server components are upgraded.
Gets or sets the user ID to be used when connecting to SQL Server.The value of the property, or if none has been supplied.
is a more secure way to specify credentials for a connection that uses SQL Server Authentication.
The user ID must be 128 characters or less.
]]>
To set the value to null, use .
Gets or sets a value that indicates whether to redirect the connection from the default SQL Server Express instance to a runtime-initiated instance running under the account of the caller.The value of the property, or if none has been supplied.
[!NOTE]
> This feature is available only with the SQL Server Express Edition. For more information on user instances, see [SQL Server Express User Instances](/sql/connect/ado-net/sql/sql-server-express-user-instances).
]]>
To set the value to null, use .
Gets an that contains the values in the .An that contains the values in the .
is unspecified, but it is the same order as the associated keys in the returned by the property. Because each instance of the always contains the same fixed set of keys, the property always returns the values corresponding to the fixed set of keys, in the same order as the keys.
## Examples
The following example first creates a new , and then iterates through all the values within the object.
[!code-csharp[SqlConnectionStringBuilder_Values#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_Values.cs#1)]
]]>
Gets or sets the name of the workstation connecting to SQL Server.The value of the property, or if none has been supplied.
To set the value to null, use .
Clears the contents of the instance.
method removes all key/value pairs from the , and resets all corresponding properties. This includes setting the property to 0, and setting the property to an empty string.
## Examples
The following example demonstrates calling the method. This example populates the with some key/value pairs, and then calls the method and shows the results.
[!code-csharp[DataWorks SqlConnectionStringBuilder_Clear#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_Clear.cs#1)]
]]>
The key to locate in the .Determines whether the contains a specific key.true if the contains an element that has the specified key; otherwise, false.
contains a fixed-size collection of key/value pairs, the method determines only if a particular key name is valid.
## Examples
The following example creates a instance, sets some of its properties, and then tries to determine whether various keys exist within the object by calling the **ContainsKey** method.
[!code-csharp[SqlConnectionStringBuilder_ContainsKey#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_ContainsKey.cs#1)]
The example displays the following output in the console window:
```
Connection string = Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True
True
True
True
False
```
]]>
is null ( in Visual Basic)
The key of the key/value pair to be removed from the connection string in this .Removes the entry with the specified key from the instance.
if the key existed within the connection string and was removed; if the key did not exist.
instance. Because the maintains a fixed-size collection of key/value pairs, calling the method simply resets the value of the key/value pair back to its default value.
Because the collection of keys supported by the is fixed, every item within the collection has a known default value. The following table lists the keys, and the value for each when the is first initialized, or after the method has been called.
|Key|Default value|
|---------|-------------------|
|Application Name|"Framework Microsoft SqlClient Data Provider" when running on .NET Framework. "Core Microsoft SqlClient Data Provider" otherwise.|
|AttachDBFilename|Empty string|
|Connection Timeout|15|
|Context Connection(Obsolete)|False|
|Current Language|Empty string|
|Data Source|Empty string|
|Encrypt|False in versions prior to 4.0, True in versions 4.0 and up|
|Enlist|True|
|Failover Partner|Empty string|
|Initial Catalog|Empty string|
|Integrated Security|False|
|Load Balance Timeout|0|
|Max Pool Size|100|
|Min Pool Size|0|
|MultipleActiveResultSets|False|
|Network Library|Empty string|
|Packet Size|8000|
|Password|Empty string|
|Persist Security Info|False|
|Pooling|True|
|Replication|False|
|Transaction Binding|Implicit Unbind|
|User ID|Empty string|
|User Instance|False|
|Workstation ID|Empty string|
## Examples
The following example converts an existing connection string from using Windows Authentication to using integrated security. The example works by removing the user name and password from the connection string, and then setting the property of the object.
> [!NOTE]
> This example includes a password to demonstrate how works with connection strings. In your applications, we recommend that you use Windows Authentication. If you must use a password, do not include a hard-coded password in your application.
[!code-csharp[SqlConnectionStringBuilder_Remove#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_Remove.cs#1)]
The example displays the following text in the console window:
```
Original: Data Source=(local);Initial Catalog=AdventureWorks;User ID=ab;Password= a1Pass@@11
Modified: Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True
Database = AdventureWorks
```
]]>
is null ( in Visual Basic)
The key to locate in the .Indicates whether the specified key exists in this instance.
if the contains an entry with the specified key; otherwise, .
method.
]]>
The key of the item to retrieve.The value corresponding to .Retrieves a value corresponding to the supplied key from this .
if was found within the connection string; otherwise, .
method lets developers safely retrieve a value from a without needing to verify that the supplied key name is a valid key name. Because **TryGetValue** does not raise an exception when you call it, passing in a nonexistent key, you do not have to look for a key before retrieving its value. Calling **TryGetValue** with a nonexistent key will place the value null (`Nothing` in Visual Basic) in the `value` parameter.
## Examples
The following example demonstrates the behavior of the **TryGetValue** method.
[!code-csharp[SqlConnectionStringBuilder_TryGetValue#1](~/../sqlclient/doc/samples/SqlConnectionStringBuilder_TryGetValue.cs#1)]
The sample displays the following results:
```
Data Source=(local)
Trusted_Connection=True
Unable to retrieve value for 'InvalidKey'
Unable to retrieve value for null key.
```
]]>
contains a null value ( in Visual Basic).
provides a more secure way to specify the password for a login attempt using SQL Server Authentication.
is comprised of a user id and a password that will be used for SQL Server Authentication. The password in a object is of type .
cannot be inherited.
Windows Authentication () remains the most secure way to log in to a SQL Server database.
to get or set a connection's object. Use to change the password for a object. For information on how a object affects connection pool behavior, see [SQL Server Connection Pooling (ADO.NET)](/sql/connect/ado-net/sql-server-connection-pooling).
An exception will be raised if a non-null object is used in a connection with any of the following connection string keywords:
- `Integrated Security = true`
- `Password`
- `User ID`
The following sample connects to a SQL Server database using :
```
// change connection string in the APP.CONFIG file
// then use the following snippet:
using System.Configuration;
System.Windows.Controls.TextBox txtUserId = new System.Windows.Controls.TextBox();
System.Windows.Controls.PasswordBox txtPwd = new System.Windows.Controls.PasswordBox();
Configuration config = Configuration.WebConfigurationManager.OpenWebConfiguration(Null);
ConnectionStringSettings connString = config.ConnectionStrings.ConnectionString["MyConnString"];
using (SqlConnection conn = new SqlConnection(connString.ConnectionString))
{
SecureString pwd = txtPwd.SecurePassword;
pwd.MakeReadOnly();
SqlCredential cred = new SqlCredential(txtUserId.Text, pwd);
conn.Credential = cred;
conn.Open();
}
```
]]>
The user id.The password; a value marked as read-only. Passing a read/write parameter will raise an .Creates an object of type .
value is allowed. An attempt to pass a null parameter in the constructor will raise an exception.
]]>
Overview of the SqlClient driver
Gets the password component of the object.The password component of the object.To be added.Overview of the SqlClient driver
Gets the user ID component of the object.The user ID component of the object.To be added.Overview of the SqlClient driver
Represents a set of data commands and a database connection that are used to fill the and update a SQL Server database. This class cannot be inherited.
, serves as a bridge between a and SQL Server for retrieving and saving data. The provides this bridge by mapping , which changes the data in the to match the data in the data source, and , which changes the data in the data source to match the data in the , using the appropriate Transact-SQL statements against the data source. The update is performed on a by-row basis. For every inserted, modified, and deleted row, the method determines the type of change that has been performed on it (`Insert`, `Update`, or `Delete`). Depending on the type of change, the `Insert`, `Update`, or `Delete` command template executes to propagate the modified row to the data source. When the fills a , it creates the necessary tables and columns for the returned data if they do not already exist. However, primary key information is not included in the implicitly created schema unless the property is set to . You may also have the create the schema of the , including primary key information, before filling it with data using `FillSchema`. For more information, see [Adding Existing Constraints to a DataSet](/sql/connect/ado-net/add-existing-constraints-to-dataset).
is used in conjunction with and to increase performance when connecting to a SQL Server database.
> [!NOTE]
> If you are using SQL Server stored procedures to edit or delete data using a `DataAdapter`, make sure that you do not use SET NOCOUNT ON in the stored procedure definition. This causes the rows affected count returned to be zero, which the `DataAdapter` interprets as a concurrency conflict. In this event, a will be thrown.
The also includes the , , , , and properties to facilitate the loading and updating of data.
When an instance of is created, the read/write properties are set to initial values. For a list of these values, see the constructor.
The , , and are generic templates that are automatically filled with individual values from every modified row through the parameters mechanism.
For every column that you propagate to the data source on , a parameter should be added to the `InsertCommand`, `UpdateCommand`, or `DeleteCommand`. The property of the object should be set to the name of the column. This setting indicates that the value of the parameter is not set manually, but is taken from the particular column in the currently processed row.
> [!NOTE]
> An will occur if the method is called and the table contains a user-defined type that is not available on the client computer. For more information, see [CLR User-Defined Types](/sql/relational-databases/clr-integration-database-objects-user-defined-types/clr-user-defined-types).
## Examples
The following example uses the , , and to select records from a database and populate a with the selected rows. The filled is then returned. To accomplish this, the method is passed an initialized , a connection string, and a query string that is a Transact-SQL SELECT statement.
[!code-csharp[SqlDataAdapter_SelectCommand Example#1](~/../sqlclient/doc/samples/SqlDataAdapter_SelectCommand.cs#1)]
]]>
Initializes a new instance of the class.
is created, the following read/write properties are set to the following initial values.
|Properties|Initial value|
|----------------|-------------------|
||`MissingMappingAction.Passthrough`|
||`MissingSchemaAction.Add`|
You can change the value of any of these properties through a separate call to the property.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlDataAdapter.SqlDataAdapter Example#1](~/../sqlclient/doc/samples/SqlDataAdapter_SqlDataAdapter.cs#1)]
]]>
A that is a Transact-SQL SELECT statement or stored procedure and is set as the property of the .Initializes a new instance of the class with the specified as the property.
constructor sets the property to the value specified in the `selectCommand` parameter.
When an instance of is created, the following read/write properties are set to the following initial values.
|Properties|Initial value|
|----------------|-------------------|
||`MissingMappingAction.Passthrough`|
||`MissingSchemaAction.Add`|
You can change the value of any of these properties through a separate call to the property.
When (or any of the other command properties) is assigned to a previously created , the is not cloned. The maintains a reference to the previously created object.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlDataAdapter_SqlDataAdapter1 Example#1](~/../sqlclient/doc/samples/SqlDataAdapter_SqlDataAdapter1.cs#1)]
]]>
A that is a Transact-SQL SELECT statement or stored procedure to be used by the property of the .A that represents the connection. If your connection string does not use , you can use to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string.Initializes a new instance of the class with a and a object.
opens and closes a if it is not already open. This can be useful in an application that must call the method for two or more objects. If the is already open, you must explicitly call **Close** or **Dispose** to close it.
When an instance of is created, the following read/write properties are set to the following initial values.
|Properties|Initial value|
|----------------|-------------------|
||`MissingMappingAction.Passthrough`|
||`MissingSchemaAction.Add`|
You can change the value of either of these properties through a separate call to the property.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlDataAdapter_SqlDataAdapter3 Example#1](~/../sqlclient/doc/samples/SqlDataAdapter_SqlDataAdapter3.cs#1)]
]]>
A that is a Transact-SQL SELECT statement or stored procedure to be used by the property of the .The connection string. If your connection string does not use , you can use and to pass the user ID and password more securely than by specifying the user ID and password as text in the connection string.Initializes a new instance of the class with a and a connection string.
constructor uses the `selectCommandText` parameter to set the property. The will create and maintain the connection created with the `selectConnectionString` parameter.
When an instance of is created, the following read/write properties are set to the following initial values.
|Properties|Initial value|
|----------------|-------------------|
||`MissingMappingAction.Passthrough`|
||`MissingSchemaAction.Add`|
You can change the value of any of these properties through a separate call to the property.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlDataAdapter_SqlDataAdapter2 Example#1](~/../sqlclient/doc/samples/SqlDataAdapter_SqlDataAdapter2.cs#1)]
]]>
Gets or sets a Transact-SQL statement or stored procedure to delete records from the data set.A used during to delete records in the database that correspond to deleted rows in the .
, if this property is not set and primary key information is present in the , the can be generated automatically if you set the property and use the . Then, any additional commands that you do not set are generated by the . This generation logic requires key column information to be present in the . For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders).
When is assigned to a previously created , the is not cloned. The maintains a reference to the previously created object.
For every column that you propagate to the data source on , a parameter should be added to the `InsertCommand`, `UpdateCommand`, or `DeleteCommand`. The `SourceColumn` property of the parameter should be set to the name of the column. This indicates that the value of the parameter is not set manually, but is taken from the particular column in the currently processed row.
## Examples
The following example creates a and sets the , , , and properties. It assumes you have already created a object.
[!code-csharp[SqlDataAdapter#1](~/../sqlclient/doc/samples/SqlDataAdapter.cs#1)]
]]>
Gets or sets a Transact-SQL statement or stored procedure to insert new records into the data source.A used during to insert records into the database that correspond to new rows in the .
, if this property is not set and primary key information is present in the , the can be generated automatically if you set the property and use the . Then, any additional commands that you do not set are generated by the . This generation logic requires key column information to be present in the . For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders).
When is assigned to a previously created , the is not cloned. The maintains a reference to the previously created object.
If execution of this command returns rows, these rows can be added to the depending on how you set the **UpdatedRowSource** property of the object.
For every column that you propagate to the data source on , a parameter should be added to `InsertCommand`, `UpdateCommand`, or `DeleteCommand`. The `SourceColumn` property of the parameter should be set to the name of the column. This indicates that the value of the parameter is not set manually, but is taken from the particular column in the currently processed row.
## Examples
The following example creates a and sets the , , , and properties. It assumes you have already created a object.
[!code-csharp[SqlDataAdapter#1](~/../sqlclient/doc/samples/SqlDataAdapter.cs#1)]
]]>
Gets or sets a Transact-SQL statement or stored procedure used to select records in the data source.A used during to select records from the database for placement in the .
is assigned to a previously created , the is not cloned. The maintains a reference to the previously created object.
If the does not return any rows, no tables are added to the , and no exception is raised.
## Examples
The following example creates a and sets the , , , and properties. It assumes you have already created a object.
[!code-csharp[SqlDataAdapter#1](~/../sqlclient/doc/samples/SqlDataAdapter.cs#1)]
]]>
Gets or sets the number of rows that are processed in each round-trip to the server.The number of rows to process per-batch.
Value is
Effect
- 0
There is no limit on the batch size.
- 1
Disables batch updating.
- >1
Changes are sent using batches of operations at a time.
When setting this to a value other than 1, all the commands associated with the have to have their **UpdatedRowSource** property set to or . An exception is thrown otherwise.
property to update a data source with changes from a . This can increase application performance by reducing the number of round-trips to the server.
Executing an extremely large batch could decrease performance. Therefore, you should test for the optimum batch size setting before implementing your application.
An is thrown if the value is set to a number less than zero.
]]>
Gets or sets a Transact-SQL statement or stored procedure used to update records in the data source.A used during to update records in the database that correspond to modified rows in the .
, if this property is not set and primary key information is present in the , the can be generated automatically if you set the property and use the . Then, any additional commands that you do not set are generated by the . This generation logic requires key column information to be present in the . For more information, see [Generating Commands with CommandBuilders](/sql/connect/ado-net/generate-commands-with-commandbuilders).
When is assigned to a previously created , the is not cloned. The maintains a reference to the previously created object.
> [!NOTE]
> If execution of this command returns rows, the updated rows may be merged with the depending on how you set the **UpdatedRowSource** property of the object.
For every column that you propagate to the data source on , a parameter should be added to `InsertCommand`, `UpdateCommand`, or `DeleteCommand`.
The `SourceColumn` property of the parameter should be set to the name of the column. This indicates that the value of the parameter is not set manually, but taken from the particular column in the currently processed row.
## Examples
The following example creates a and sets the , , and properties. It assumes you have already created a object.
[!code-csharp[SqlDataAdapter#1](~/../sqlclient/doc/samples/SqlDataAdapter.cs#1)]
]]>
Occurs during after a command is executed against the data source. The attempt to update is made, so the event fires.
, there are two events that occur per data row updated. The order of execution is as follows:
1. The values in the are moved to the parameter values.
2. The event is raised.
3. The command executes.
4. If the command is set to `FirstReturnedRecord`, the first returned result is placed in the .
5. If there are output parameters, they are placed in the .
6. The event is raised.
7. is called.
## Examples
The following example shows how to use both the and events.
The event returns this output:
event args: (command=Microsoft.Data.SqlClient.SqlCommand commandType=2 status=0)
The event returns this output:
event args: (command=Microsoft.Data.SqlClient.SqlCommand commandType=2 recordsAffected=1 row=System.Data.DataRow[37] status=0)
[!code-csharp[SqlDataAdapter_RowUpdated Example#1](~/../sqlclient/doc/samples/SqlDataAdapter_RowUpdated.cs#1)]
]]>
Occurs during before a command is executed against the data source. The attempt to update is made, so the event fires.
, there are two events that occur per data row updated. The order of execution is as follows:
1. The values in the are moved to the parameter values.
2. The event is raised.
3. The command executes.
4. If the command is set to `FirstReturnedRecord`, the first returned result is placed in the .
5. If there are output parameters, they are placed in the .
6. The event is raised.
7. is called.
## Examples
The following example shows how to use both the and events.
The event returns this output:
event args: (command=Microsoft.Data.SqlClient.SqlCommand commandType=2 status=0)
The event returns this output:
event args: (command=Microsoft.Data.SqlClient.SqlCommand commandType=2 recordsAffected=1 row=System.Data.DataRow[37] status=0)
[!code-csharp[SqlDataAdapter_RowUpdated Example#1](~/../sqlclient/doc/samples/SqlDataAdapter_RowUpdated.cs#1)]
]]>
To be added.To be added.To be added.
To be added.To be added.To be added.
Provides a way of reading a forward-only stream of rows from a SQL Server database. This class cannot be inherited.
, you must call the method of the object, instead of directly using a constructor.
While the is being used, the associated is busy serving the , and no other operations can be performed on the other than closing it. This is the case until the method of the is called. For example, you cannot retrieve output parameters until after you call .
Changes made to a result set by another process or thread while data is being read may be visible to the user of the `SqlDataReader`. However, the precise behavior is timing dependent.
and are the only properties that you can call after the is closed. Although the property may be accessed while the exists, always call before returning the value of to guarantee an accurate return value.
When using sequential access (), an will be raised if the position is advanced and another read operation is attempted on the previous column.
> [!NOTE]
> For optimal performance, avoids creating unnecessary objects or making unnecessary copies of data. Therefore, multiple calls to methods such as return a reference to the same object. Use caution if you are modifying the underlying value of the objects returned by methods such as .
## Examples
The following example creates a , a , and a . The example reads through the data, writing it out to the console window. The code then closes the . The is closed automatically at the end of the `using` code block.
[!code-csharp[SqlDataReader_Read Example#1](~/../sqlclient/doc/samples/SqlDataReader_Read.cs#1)]
]]>
Gets the associated with the .The associated with the .To be added.
Gets a value that indicates the depth of nesting for the current row.The depth of nesting for the current row.
Gets the number of columns in the current row.When not positioned in a valid recordset, 0; otherwise the number of columns in the current row. The default is -1.
to 0. However. this should not be confused with a query that returns 0 rows (such as SELECT * FROM *table* WHERE 1 = 2) in which case returns the number of columns in the table, including hidden fields. Use to exclude hidden fields.
]]>
There is no current connection to an instance of SQL Server.
Gets a value that indicates whether the contains one or more rows.
if the contains one or more rows; otherwise .To be added.
Retrieves a Boolean value that indicates whether the specified instance has been closed.
if the specified instance is closed; otherwise .
instance that is closed.
]]>
The zero-based column ordinal.Gets the value of the specified column in its native format given the column ordinal.The value of the specified column in its native format.To be added.The index passed was outside the range of 0 through .
The column name.Gets the value of the specified column in its native format given the column name.The value of the specified column in its native format.
No column with the specified name was found.
Gets the number of rows changed, inserted, or deleted by execution of the Transact-SQL statement.The number of rows changed, inserted, or deleted; 0 if no rows were affected or the statement failed; and -1 for SELECT statements.
and are the only properties that you can call after the is closed.
]]>
Gets the information with the .The associated with the .To be added.
Gets the number of fields in the that are not hidden.The number of fields that are not hidden.
are visible. For example, a SELECT on a partial primary key returns the remaining parts of the key as hidden fields. The hidden fields are always appended behind the visible fields.
]]>
Closes the object.
method is called when you are through using the before using the associated for any other purpose. The `Close` method may either be called directly or through the `Dispose` method, disposing directly or in the context of [the using statement](/dotnet/csharp/language-reference/language-specification/statements#the-using-statement) block.
The `Close` method populates the values for output parameters, return values and `RecordsAffected` on the by consuming any pending results. This may be a long operation depending on the amount of data to be consumed. If output values, return values, and `RecordsAffected` are not important to your application, the time to close may be shortened by calling the method of the associated object before the `Close` method is called.
> [!CAUTION]
> Do not call `Close` or `Dispose` on a Connection, a DataReader, or any other managed object in the `Finalize` method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a `Finalize` method in your class definition. For more information, see [Garbage Collection](/dotnet/standard/garbage-collection/).
## Examples
The following example creates a , a , and a . The example reads through the data, writing it out to the console window. The code then closes the . The is closed automatically at the end of the `using` code block.
[!code-csharp[SqlDataReader_Close Example#1](~/../sqlclient/doc/samples/SqlDataReader_Close.cs#1)]
]]>
The zero-based column ordinal.Gets the value of the specified column as a Boolean.The value of the column.
to check for null values before calling this method.
]]>
The specified cast is not valid.
The zero-based column ordinal.Gets the value of the specified column as a byte.The value of the specified column as a byte.
to check for null values before calling this method.
]]>
The specified cast is not valid.
The zero-based column ordinal.The index within the field from which to begin the read operation.The buffer into which to read the stream of bytes.The index within the where the write operation is to start.The maximum length to copy into the buffer.Reads a stream of bytes from the specified column offset into the buffer an array starting at the given buffer offset.The actual number of bytes read.
returns the number of available bytes in the field. Most of the time this is the exact length of the field. However, the number returned may be less than the true length of the field if `GetBytes` has already been used to obtain bytes from the field. This may be the case, for example, if the is reading a large data structure into a buffer. For more information, see the `SequentialAccess` setting for .
If you pass a buffer that is `null`, returns the length of the entire field in bytes, not the remaining size based on the buffer offset parameter.
No conversions are performed; therefore, the data retrieved must already be a byte array.
]]>
The zero-based column ordinal.Gets the value of the specified column as a single character.The value of the specified column.
.
]]>
The specified cast is not valid.
The zero-based column ordinal.The index within the field from which to begin the read operation.The buffer into which to read the stream of bytes.The index within the where the write operation is to start.The maximum length to copy into the buffer.Reads a stream of characters from the specified column offset into the buffer as an array starting at the given buffer offset.The actual number of characters read.
returns the number of available characters in the field. Frequently this is the exact length of the field. However, the number returned may be less than the true length of the field if `GetChars` has already been used to obtain characters from the field. This may be the case, for example, if the is reading a large data structure into a buffer. For more information, see the `SequentialAccess` setting for .
The actual number of characters read can be less than the requested length, if the end of the field is reached. If you pass a buffer that is `null`, returns the length of the entire field in characters, not the remaining size based on the buffer offset parameter.
No conversions are performed; therefore. the data retrieved must already be a character array.
> [!NOTE]
> The method returns 0 when `dataIndex` is negative.
]]>
Gets the read-only column schema collection.The read-only column schema collection).
method, which enables the use of the interface to populate the schema metadata without using a .
]]>
The zero-based ordinal position of the column to find.Gets a string representing the data type of the specified column.The string representing the data type of the specified column.
The zero-based column ordinal.Gets the value of the specified column as a object.The value of the specified column.
object.
Call to check for null values before calling this method.
]]>
The specified cast is not valid.
The zero-based column ordinal.Retrieves the value of the specified column as a object.The value of the specified column.
object.
Call to check for null values before calling this method.
]]>
The specified cast is not valid.
The zero-based column ordinal.Gets the value of the specified column as a object.The value of the specified column.
object.
Call to check for null values before calling this method.
]]>
The specified cast is not valid.
The zero-based column ordinal.Gets the value of the specified column as a double-precision floating point number.The value of the specified column.
to check for null values before calling this method.
]]>
The specified cast is not valid.
Returns an that iterates through the .An for the .
The zero-based column ordinal.Gets the that is the data type of the object.The that is the data type of the object. If the type does not exist on the client, in the case of a User-Defined Type (UDT) returned from the database, **GetFieldType** returns null.To be added.
The type of the value to be returned.The column to be retrieved.Synchronously gets the value of the specified column as a type. is the asynchronous version of this method.The returned type object.
.|
For more information, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
]]>
The connection drops or is closed during the data retrieval.
The is closed during the data retrieval.
There is no data ready to be read (for example, the first hasn't been called, or returned false).
Tried to read a previously-read column in sequential mode.
There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream.Trying to read a column that does not exist.The value of the column was null ( == ), retrieving a non-SQL type.
doesn't match the type returned by SQL Server or cannot be cast.
The type of the value to be returned.The column to be retrieved.The cancellation instruction, which propagates a notification that operations should be canceled. This does not guarantee the cancellation. A setting of makes this method equivalent to . The returned task must be marked as cancelled.Asynchronously gets the value of the specified column as a type. is the synchronous version of this method.The returned type object.
.|
For more information, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
]]>
The connection drops or is closed during the data retrieval.
The is closed during the data retrieval.
There is no data ready to be read (for example, the first hasn't been called, or returned false).
Tried to read a previously-read column in sequential mode.
There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream.Trying to read a column that does not exist.The value of the column was null ( == ), retrieving a non-SQL type.
doesn't match the type returned by SQL Server or cannot be cast.
The zero-based column ordinal.Gets the value of the specified column as a single-precision floating point number.The value of the specified column.
to check for null values before calling this method.
]]>
The specified cast is not valid.
The zero-based column ordinal.Gets the value of the specified column as a globally unique identifier (GUID).The value of the specified column.
to check for null values before calling this method.
]]>
The specified cast is not valid.
The zero-based column ordinal.Gets the value of the specified column as a 16-bit signed integer.The value of the specified column.
to check for null values before calling this method.
]]>
The specified cast is not valid.
The zero-based column ordinal.Gets the value of the specified column as a 32-bit signed integer.The value of the specified column.
to check for null values before calling this method.
]]>
The specified cast is not valid.
The zero-based column ordinal.Gets the value of the specified column as a 64-bit signed integer.The value of the specified column.
to check for null values before calling this method.
]]>
The specified cast is not valid.
The zero-based column ordinal.Gets the name of the specified column.The name of the specified column.To be added.
The name of the column.Gets the column ordinal, given the name of the column.The zero-based column ordinal.
method.
[!code-csharp[SqlDataReader_GetOrdinal#1](~/../sqlclient/doc/samples/SqlDataReader_GetOrdinal.cs#1)]
]]>
The name specified is not a valid column name.
An representing the column ordinal.Gets an that is a representation of the underlying provider-specific field type.Gets an that is a representation of the underlying provider-specific field type.To be added.
An representing the column ordinal.Gets an that is a representation of the underlying provider specific value.An that is a representation of the underlying provider specific value.To be added.
An array of into which to copy the column values.Gets an array of objects that are a representation of the underlying provider specific values.The array of objects that are a representation of the underlying provider specific values.To be added.
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column.
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Gets the value of the specified column as .The value of the column expressed as a .To be added.
The zero-based column ordinal.Gets the value of the specified column as .The value of the column expressed as a .To be added.
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Gets the value of the specified column as a .The value of the column expressed as a .
The zero-based column ordinal.Returns the data value in the specified column as a SQL Server type.The value of the column expressed as a .
returns data using the native SQL Server types. To retrieve data using the .NET Framework types, see .
]]>
An array of into which to copy the values. The column values are expressed as SQL Server types.Fills an array of that contains the values for all the columns in the record, expressed as SQL Server types.An integer indicating the number of columns copied.
array does not need to match the number of columns in the record. You can pass an array that contains fewer than the number of columns contained in the record. Only the amount of data the array holds is copied to the array, starting at the column with ordinal 0. You can also pass an array whose length is more than the number of columns contained in the resulting row. Any remaining columns are untouched.
]]>
is null.
The zero-based column ordinal.Gets the value of the specified column as an XML value.A value that contains the XML stored within the corresponding field.
to check for null values before calling this method.
]]>
The index passed was outside the range of 0 to - 1An attempt was made to read or access columns in a closed .The retrieved data is not compatible with the type.
Returns a that describes the column metadata of the .A that describes the column metadata.
method returns the following metadata about each column:
|DataReader column|Description|
|-----------------------|-----------------|
|AllowDBNull|Set if the consumer can set the column to a null value or if the provider cannot determine whether the consumer can set the column to a null value. Otherwise, not set. A column may contain null values, even if it cannot be set to a null value.|
|BaseCatalogName|The name of the catalog in the data store that contains the column. NULL if the base catalog name cannot be determined. The default of this column is a null value.|
|BaseColumnName|The name of the column in the data store. This might be different than the column name returned in the ColumnName column if an alias was used. A null value if the base column name cannot be determined or if the rowset column is derived, but not identical to, a column in the data store. The default of this column is a null value.|
|BaseSchemaName|The name of the schema in the data store that contains the column. A null value if the base schema name cannot be determined. The default of this column is a null value.|
|BaseServerName|The name of the instance of Microsoft SQL Server used by the .|
|BaseTableName|The name of the table or view in the data store that contains the column. A null value if the base table name cannot be determined. The default of this column is a null value.|
|ColumnName|The name of the column; this might not be unique. If this cannot be determined, a null value is returned. This name always reflects the most recent renaming of the column in the current view or command text.|
|ColumnOrdinal|The zero-based ordinal of the column. This column cannot contain a null value.|
|ColumnSize|The maximum possible length of a value in the column. For columns that use a fixed-length data type, this is the size of the data type. For `nvarchar(MAX)`, `varchar(MAX)`, and `varbinary(MAX)` columns stored in a SQL Server database, the maximum size is 2GB. If these columns are stored and accessed as files, the limit on maximum size is imposed by the file system. This value changes when using the `Type System Version` keyword in the connection string. For new types they are represented as downlevel types. The MAX data types return the normal 4k for `nvarchar` and 8000 for `varchar`. For more information, see the [Transact-SQL reference](/sql/t-sql/language-reference).|
|DataTypeName|Returns a string representing the data type of the specified column.|
|IsAliased|`true`: The column name is an alias.
`false`: The column name is not an alias.|
|IsAutoIncrement|`true`: The column assigns values to new rows in fixed increments.
`false`: The column does not assign values to new rows in fixed increments. The default of this column is `false`.|
|IsColumnSet|`true`: The column is a sparse column that is a member of a column set.|
|IsExpression|`true`: The column is an expression.
`false`: The column is not an expression.|
|IsHidden|`true`: The column is hidden.
`false`: The column is not hidden.|
|IsIdentity|`true`: The column is an identity column.
`false`: The column is not an identity column.|
|IsKey|`true`: The column is one of a set of columns in the rowset that, taken together, uniquely identify the row. The set of columns with `IsKey` set to `true` must uniquely identify a row in the rowset. There is no requirement that this set of columns is a minimal set of columns. This set of columns may be generated from a base table primary key, a unique constraint or a unique index.
`false`: The column is not required to uniquely identify the row.|
|IsLong|`true`: The column contains a Binary Long Object (BLOB) that contains very long data. The definition of very long data is provider-specific.
`false`: The column does not contain a Binary Long Object (BLOB) that contains very long data.|
|IsReadOnly|`true`: The column cannot be modified.
`false`: The column can be modified.|
|IsRowVersion|`true`: The column contains a persistent row identifier that cannot be written to, and has no meaningful value except to identity the row.
`false`: The column does not contain a persistent row identifier that cannot be written to, and has no meaningful value except to identity the row.|
|IsUnique|`true`: Column is of type `timestamp`.
`false`: Column is not of type `timestamp`.|
|NonVersionedProviderType|The type of the column irrespective of the current `Type System Version` specified in the connection string. The returned value is from the enumeration.|
|NumericPrecision|If `ProviderType` is a numeric data type, this is the maximum precision of the column. The precision depends on the definition of the column. If `ProviderType` is not a numeric data type, this is 255.|
|NumericScale|If `ProviderType` is DBTYPE_DECIMAL or DBTYPE_NUMERIC, the number of digits to the right of the decimal point. Otherwise, this is 255.|
|ProviderSpecificDataType|Returns the provider-specific data type of the column based on the `Type System Version` keyword in the connection string.|
|ProviderType|The indicator of the column's data type. If the data type of the column varies from row to row, this must be Object. This column cannot contain a null value.|
|UdtAssemblyQualifiedName|If the column is a user-defined type (UDT), this is the qualified name of the UDT's assembly as per . If the column is not a UDT, this is null.|
|XmlSchemaCollectionDatabase|The name of the database where the schema collection for this XML instance is located, if the row contains information about an XML column. This value is `null` (`Nothing` in Visual Basic) if the collection is defined within the current database. It is also null if there is no schema collection, in which case the `XmlSchemaCollectionName` and `XmlSchemaCollectionOwningSchema` columns are also null.|
|XmlSchemaCollectionName|The name of the schema collection for this XML instance, if the row contains information about an XML column. This value is `null` (`Nothing` in Visual Basic) if there is no associated schema collection. If the value is null, the `XmlSchemaCollectionDatabase` and `XmlSchemaCollectionOwningSchema` columns are also null.|
|XmlSchemaCollectionOwningSchema|The owning relational schema where the schema collection for this XML instance is located, if the row contains information about an XML column. This value is `null` (`Nothing` in Visual Basic) if the collection is defined within the current database. It is also null if there is no schema collection, in which case the `XmlSchemaCollectionDatabase` and `XmlSchemaCollectionName` columns are also null.|
> [!NOTE]
> To make sure that metadata columns return the correct information, you must call with the `behavior` parameter set to `KeyInfo`. Otherwise, some of the columns in the schema table may return default, null, or incorrect data.
]]>
The is closed.
The zero-based column ordinal.Retrieves binary, image, varbinary, UDT, and variant data types as a .A stream object.
defaults to the value of ; but you can modify via .
Null values will be returned as an empty (zero bytes) .
will raise an exception when used on an object returned by when is in effect.
exceptions raised from are thrown as exceptions; check the inner exception for the .
The following members are not available for objects returned by :
- BeginWrite
- EndWrite
- Length
- Position
- Seek
- SetLength
- Write
- WriteByte
- WriteTimeout
For more information, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
]]>
The connection drops or is closed during the data retrieval.
The is closed during the data retrieval.
There is no data ready to be read (for example, the first hasn't been called, or returned false).
Tried to read a previously-read column in sequential mode.
There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream.Trying to read a column that does not exist.The returned type was not one of the types below:
- binary
- image
- varbinary
- udt
The zero-based column ordinal.Gets the value of the specified column as a string.The value of the specified column.
to check for null values before calling this method.
]]>
The specified cast is not valid.
The column to be retrieved.Retrieves Char, NChar, NText, NVarChar, text, varChar, and Variant data types as a .The returned object.
exceptions raised from are thrown as exceptions; check the inner exception for the .
Null values will be returned as an empty (zero bytes) .
will raise an exception when used on an object returned by when is in effect.
For more information, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
]]>
The connection drops or is closed during the data retrieval.
The is closed during the data retrieval.
There is no data ready to be read (for example, the first hasn't been called, or returned false).
Tried to read a previously-read column in sequential mode.
There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream.Trying to read a column that does not exist.The returned type was not one of the types below:
- char
- nchar
- ntext
- nvarchar
- text
- varchar
The zero-based column ordinal.Retrieves the value of the specified column as a object.The value of the specified column.
object.
Call to check for null values before calling this method.
]]>
The specified cast is not valid.
The zero-based column ordinal.Gets the value of the specified column in its native format.This method returns for null database columns.
returns data using the .NET Framework types.
]]>
An array of into which to copy the attribute columns.Populates an array of objects with the column values of the current row.The number of instances of in the array.
array that contains fewer than the number of columns contained in the resulting row. Only the amount of data the array holds is copied to the array. You can also pass an array whose length is more than the number of columns contained in the resulting row.
This method returns for null database columns.
## Examples
The following example demonstrates using a correctly sized array to read all values from the current row in the supplied . In addition, the sample demonstrates using a fixed-sized array that could be either smaller or larger than the number of available columns.
[!code-csharp[DataTableReader_GetValues#2](~/../sqlclient/doc/samples/DataTableReader_GetValues.cs#2)]
]]>
The value of the specified column.Retrieves data of type XML as an .The returned object.
object returned by does not support asynchronous operations. If you require asynchronous operations on an , cast the XML column to an NVARCHAR(MAX) on the server and use with .
exceptions raised from are thrown as exceptions; check the inner exception for the .
will raise an exception when used on an object returned by when is in effect.
For more information, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
]]>
The connection drops or is closed during the data retrieval.
The is closed during the data retrieval.
There is no data ready to be read (for example, the first hasn't been called, or returned false).
Trying to read a previously read column in sequential mode.
There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream.Trying to read a column that does not exist.The returned type was not xml.
A enumeration.Determines whether the specified matches that of the .
if the specified is true, otherwise.
The zero-based column ordinal.Gets a value that indicates whether the column contains non-existent or missing values.
if the specified column value is equivalent to ; otherwise .
, , and so on) to avoid raising an error.
[!code-csharp[SqlDataReader_IsDBNull#1](~/../sqlclient/doc/samples/SqlDataReader_IsDBNull.cs#1)]
]]>
The zero-based column to be retrieved.The cancellation instruction, which propagates a notification that operations should be canceled. This does not guarantee the cancellation. A setting of makes this method equivalent to . The returned task must be marked as cancelled.An asynchronous version of , which gets a value that indicates whether the column contains non-existent or missing values.
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.
if the specified column value is equivalent to otherwise .
The connection drops or is closed during the data retrieval.
The is closed during the data retrieval.
There is no data ready to be read (for example, the first hasn't been called, or returned false).
Trying to read a previously read column in sequential mode.
There was an asynchronous operation in progress. This applies to all Get* methods when running in sequential mode, as they could be called while reading a stream.Trying to read a column that does not exist.
Advances the data reader to the next result, when reading the results of batch Transact-SQL statements.
if there are more result sets; otherwise .
The cancellation instruction.An asynchronous version of , which advances the data reader to the next result, when reading the results of batch Transact-SQL statements.
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.A task representing the asynchronous operation.
Calling more than once for the same instance before task completion.SQL Server returned an error while executing the command text.
Advances the to the next record.
if there are more rows; otherwise .
is before the first record. Therefore, you must call to begin accessing any data.
Only one `SqlDataReader` per associated may be open at a time, and any attempt to open another will fail until the first one is closed. Similarly, while the `SqlDataReader` is being used, the associated `SqlConnection` is busy serving it until you call .
## Examples
The following example creates a , a , and a . The example reads through the data, writing it out to the console window. The code then closes the . The is closed automatically at the end of the `using` code block.
[!code-csharp[SqlDataReader_Read Example#1](~/../sqlclient/doc/samples/SqlDataReader_Read.cs#1)]
]]>
SQL Server returned an error while executing the command text.
The cancellation instruction.An asynchronous version of , which advances the to the next record.
The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Exceptions will be reported via the returned Task object.A task representing the asynchronous operation.
is set to `Default`, reads the entire row before returning the Task.
For more information, including code samples, about asynchronous programming in the .NET Framework Data Provider for SQL Server, see [Asynchronous Programming](/sql/connect/ado-net/asynchronous-programming).
> [!NOTE]
> When reading large data (binary/text), it is recommended to use for optimal performance.
]]>
Calling more than once for the same instance before task completion.SQL Server returned an error while executing the command text.
The object represents a query notification dependency between an application and an instance of SQL Server. An application can create a object and register to receive notifications via the event handler.
is ideal for caching scenarios, where your ASP.NET application or middle-tier service needs to keep certain information cached in memory. allows you to receive notifications when the original data in the database changes so that the cache can be refreshed.
To set up a dependency, you need to associate a object to one or more objects. To receive notifications, you need to subscribe to the event. For more information about the requirements for creating queries for notifications, see [Working with Query Notifications](/sql/relational-databases/native-client/features/working-with-query-notifications).
> [!NOTE]
> was designed to be used in ASP.NET or middle-tier services where there is a relatively small number of servers having dependencies active against the database. It was not designed for use in client applications, where hundreds or thousands of client computers would have objects set up for a single database server. If you are developing an application where you need reliable sub-second notifications when data changes, review the sections [Planning an Efficient Query Notifications Strategy](https://docs.microsoft.com/previous-versions/sql/sql-server-2008-r2/ms187528(v=sql.105)#planning-an-efficient-query-notifications-strategy) and [Alternatives to Query Notifications](https://docs.microsoft.com/previous-versions/sql/sql-server-2008-r2/ms187528(v=sql.105)#alternatives-to-query-notifications) in the [Planning for Notifications](https://docs.microsoft.com/previous-versions/sql/sql-server-2008-r2/ms187528(v%3dsql.105)) article.
For more information, see [Query Notifications in SQL Server](/sql/connect/ado-net/sql/query-notifications-sql-server) and [Building Notification Solutions](https://docs.microsoft.com/previous-versions/sql/sql-server-2005/ms171065(v%3dsql.90)).
> [!NOTE]
> The event may be generated on a different thread from the thread that initiated command execution.
Query notifications are supported only for SELECT statements that meet a list of specific requirements.
]]>
Creates a new instance of the class with the default settings.
object using the default Service Broker service name and time-out. At some point after construction, you must use the method to associate one or more commands to this object.
Query notifications are supported only for SELECT statements that meet a list of specific requirements. For more information, see [SQL Server Service Broker](/sql/database-engine/configure-windows/sql-server-service-broker) and [Working with Query Notifications](/sql/connect/oledb/features/working-with-query-notifications).
]]>
The object to associate with this object. The constructor will set up a object and bind it to the command.Creates a new instance of the class and associates it with the parameter.
class, and binds it to a object.
Query notifications are supported only for SELECT statements that meet a list of specific requirements. For more information, see [SQL Server Service Broker](/sql/database-engine/configure-windows/sql-server-service-broker) and [Working with Query Notifications](/sql/connect/oledb/features/working-with-query-notifications).
]]>
The parameter is NULL.The object already has a object assigned to its property, and that is not associated with this dependency.
The object to associate with this object. The constructor sets up a object and bind it to the command.The notification request options to be used by this dependency. to use the default service.The time-out for this notification in seconds. The default is 0, indicating that the server's time-out should be used.Creates a new instance of the class, associates it with the parameter, and specifies notification options and a time-out value.
The parameter is NULL.The time-out value is less than zero.The object already has a object assigned to its property and that is not associated with this dependency.
An attempt was made to create a **SqlDependency** instance from within SQLCLR.
Gets a value that indicates whether one of the result sets associated with the dependency has changed.A Boolean value indicating whether one of the result sets has changed.
event, you can check the property to determine if the query results have changed.
The property does not necessarily imply a change in the data. Other circumstances, such as time-out expired and failure to set the notification request, also generate a change event.
]]>
Gets a value that uniquely identifies this instance of the class.A string representation of a GUID that is generated for each instance of the class.
property is used to uniquely identify a given instance.
]]>
Occurs when a notification is received for any of the commands associated with this object.
occurs when the results for the associated command change. If you are not using , you can check the property to determine whether the query results have changed.
The event does not necessarily imply a change in the data. Other circumstances, such as time-out expired and failure to set the notification request, also generate .
]]>
A object containing a statement that is valid for notifications.Associates a object with this instance.
The parameter is null.The object already has a object assigned to its property, and that is not associated with this dependency.
The connection string for the instance of SQL Server from which to obtain change notifications.Starts the listener for receiving dependency change notifications from the instance of SQL Server specified by the connection string.
if the listener initialized successfully; if a compatible listener already exists.
for receiving dependency notifications from the instance of SQL Server specified by the `connectionString` parameter. This method may be called more than once with different connection strings for multiple servers.
For additional remarks, see .
]]>
The parameter is NULL.The parameter is the same as a previous call to this method, but the parameters are different.
The method was called from within the CLR.The caller does not have the required code access security (CAS) permission.A subsequent call to the method has been made with an equivalent parameter with a different user, or a user that does not default to the same schema.
Also, any underlying **SqlClient** exceptions.
The connection string for the instance of SQL Server from which to obtain change notifications.An existing SQL Server Service Broker queue to be used. If , the default queue is used.Starts the listener for receiving dependency change notifications from the instance of SQL Server specified by the connection string using the specified SQL Server Service Broker queue.
if the listener initialized successfully; if a compatible listener already exists.
for receiving dependency notifications from the instance of SQL Server specified by the `connectionString` parameter. This method may be called more than once with different connection strings for multiple servers.
If no queue name is specified, creates a temporary queue and service in the server that is used for the entire process, even if the process involves more than one . The queue and service are automatically removed upon application shutdown.
For additional remarks, see .
]]>
The parameter is NULL.The parameter is the same as a previous call to this method, but the parameters are different.
The method was called from within the CLR.The caller does not have the required code access security (CAS) permission.A subsequent call to the method has been made with an equivalent parameter but a different user, or a user that does not default to the same schema.
Also, any underlying **SqlClient** exceptions.
Connection string for the instance of SQL Server that was used in a previous call.Stops a listener for a connection specified in a previous call.
if the listener was completely stopped; if the was unbound from the listener, but there are is at least one other using the same listener.
method must be called for each call. A given listener only shuts down fully when it receives the same number of requests as requests.
]]>
The parameter is NULL.The method was called from within SQLCLR.The caller does not have the required code access security (CAS) permission.An underlying **SqlClient** exception occurred.
Connection string for the instance of SQL Server that was used in a previous call.The SQL Server Service Broker queue that was used in a previous call.Stops a listener for a connection specified in a previous call.
if the listener was completely stopped; if the was unbound from the listener, but there is at least one other using the same listener.
method must be called for each call. A given listener only shuts down fully when it receives the same number of requests as requests.
]]>
The parameter is NULL.The method was called from within SQLCLR.The caller does not have the required code access security (CAS) permission.And underlying **SqlClient** exception occurred.
Collects information relevant to a warning or error returned by SQL Server.
is created and managed by the , which in turn is created by the class.
Messages with a severity level of 10 or less are informational and indicate problems caused by mistakes in information that a user has entered. Severity levels from 11 through 16 are generated by the user, and can be corrected by the user. Severity levels from 17 through 25 indicate software or hardware errors. When a level 17, 18, or 19 error occurs, you can continue working, although you might not be able to execute a particular statement.
The remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server usually closes the . However, the user can reopen the connection and continue. In both cases, a is generated by the method executing the command.
For more information on errors generated by SQL Server, see [Cause and Resolution of Database Engine Errors](https://msdn.microsoft.com/library/ms365262.aspx). For more information about severity levels, see [Database Engine Error Severities](https://msdn.microsoft.com/library/ms164086.aspx).
## Examples
The following example displays each within the collection.
[!code-csharp[SqlError_ToString Example#1](~/../sqlclient/doc/samples/SqlError_ToString.cs#1)]
]]>
Gets the severity level of the error returned from SQL Server.A value from 1 to 25 that indicates the severity level of the error. The default is 0.
remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server usually closes the . However, the user can reopen the connection and continue. In both cases, a is generated by the method executing the command.
For more information on errors generated by SQL Server, see [Database Engine Events and Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors).
## Examples
The following example displays each within the collection.
[!code-csharp[SqlError_State Example#1](~/../sqlclient/doc/samples/SqlError_State.cs#1)]
]]>
Gets the line number within the Transact-SQL command batch or stored procedure that contains the error.The line number within the Transact-SQL command batch or stored procedure that contains the error.
within the collection.
[!code-csharp[SqlError.State Example#1](~/../sqlclient/doc/samples/SqlError_State.cs#1)]
]]>
Gets the text describing the error.The text describing the error. For more information on errors generated by SQL Server, see Database Engine Events and Errors.
within the collection.
[!code-csharp[SqlError.State Example#1](~/../sqlclient/doc/samples/SqlError_State.cs#1)]
]]>
Gets a number that identifies the type of error.The number that identifies the type of error.
This number corresponds to an entry in the `master.dbo.sysmessages` table.|Typically greater than 0|No|
|Connection timeout|-2|0|Yes (Number = 258)|
|Communication error (non-LocalDB)|Win32 error code|0|Yes (Number = Win32 error code)|
|Communication error (LocalDB)|Win32 error code|0|No|
|Encryption capability mismatch|20|0|No|
|Failed to start LocalDB|Win32 error code|0|No|
|Read-only routing failure|0|0|No|
|Server had severe error processing query|0|0|No|
|Processed cancellation while parsing results|0|0|No|
|Failed to create user instance|0|0|No|
For more information on errors generated by SQL Server, see [Database Engine Events and Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors).
## Examples
The following example displays each within the collection.
[!code-csharp[SqlError.State Example#1](~/../sqlclient/doc/samples/SqlError_State.cs#1)]
]]>
Gets the name of the stored procedure or remote procedure call (RPC) that generated the error.The name of the stored procedure or RPC. For more information on errors generated by SQL Server, see Database Engine Events and Errors.
within the collection.
[!code-csharp[SqlError.State Example#1](~/../sqlclient/doc/samples/SqlError_State.cs#1)]
]]>
Gets the name of the instance of SQL Server that generated the error.The name of the instance of SQL Server.
within the collection.
[!code-csharp[SqlError.State Example#1](~/../sqlclient/doc/samples/SqlError_State.cs#1)]
]]>
Gets the name of the provider that generated the error.The name of the provider that generated the error.
within the collection.
[!code-csharp[SqlError.State Example#1](~/../sqlclient/doc/samples/SqlError_State.cs#1)]
]]>
Some error messages can be raised at multiple points in the code for the Database Engine. For example, an 1105 error can be raised for several different conditions. Each specific condition that raises an error assigns a unique state code.The state code.
within the collection.
[!code-csharp[SqlError.State Example#1](~/../sqlclient/doc/samples/SqlError_State.cs#1)]
]]>
Gets the complete text of the error message.The complete text of the error.
, and the stack trace. For example:
SqlError:UserId or Password not valid. \
## Examples
The following example displays each within the collection.
[!code-csharp[SqlError_ToString Example#1](~/../sqlclient/doc/samples/SqlError_ToString.cs#1)]
]]>
Collects all errors generated by the .NET Framework Data Provider for SQL Server. This class cannot be inherited.
to collect instances of the class. always contains at least one instance of the class.
## Examples
The following example displays each within the collection.
[!code-csharp[SqlError_ToString Example#1](~/../sqlclient/doc/samples/SqlError_ToString.cs#1)]
]]>
Gets the number of errors in the collection.The total number of errors in the collection.
within the collection.
[!code-csharp[SqlError_ToString Example#1](~/../sqlclient/doc/samples/SqlError_ToString.cs#1)]
]]>
The zero-based index of the error to retrieve.Gets the error at the specified index.A that contains the error at the specified index.
within the collection.
[!code-csharp[SqlError_ToString Example#1](~/../sqlclient/doc/samples/SqlError_ToString.cs#1)]
]]>
Index parameter is outside array bounds.
For a description of this member, see .
if access to the is synchronized (thread safe); otherwise, .
instance is cast to an interface.
]]>
For a description of this member, see .An object that can be used to synchronize access to the .
instance is cast to an interface.
]]>
The to copy elements into.The index from which to start copying into the parameter.Copies the elements of the collection into an , starting at the specified index.To be added.The sum of and the number of elements in the collection is greater than the of the .The is .The is not valid for .
The to copy the elements into.The index from which to start copying into the parameter.Copies the elements of the collection into a , starting at the specified index.To be added.The sum of and the number of elements in the collection is greater than the length of the .The is .The is not valid for .
Returns an enumerator that iterates through the .An for the .
The exception that is thrown when SQL Server returns a warning or error. This class cannot be inherited.
always contains at least one instance of .
Messages that have a severity level of 10 or less are informational and indicate problems caused by mistakes in information that a user has entered. Severity levels from 11 through 16 are generated by the user, and can be corrected by the user. Severity levels from 17 through 25 indicate software or hardware errors. When a level 17, 18, or 19 error occurs, you can continue working, although you might not be able to execute a particular statement.
The remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server ordinarily closes the . However, the user can reopen the connection and continue. In both cases, a is generated by the method executing the command.
For information about the warning and informational messages sent by SQL Server, see [Database Engine Events and Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors). The class maps to SQL Server severity.
The following is general information on handling exceptions. Your code should catch exceptions to prevent the application from crashing and to allow displaying a relevant error message to the user. You can use database transactions to ensure that the data is consistent regardless of what happens in the client application (including a crash). Features like System.Transaction.TransactionScope or the BeginTransaction method (in System.Data.OleDb.OleDbConnection, System.Data.ODBC.ODBCConnection, and Microsoft.Data.SqlClient.SqlConnection) ensure consistent data regardless of exceptions raised by a provider. Transactions can fail, so catch failures and retry the transaction.
Note that beginning with .NET Framework 4.5, can return an inner .
The exception class of a .NET Framework data provider reports provider-specific errors. For example System.Data.Odbc has OdbcException, System.Data.OleDb has OleDbException, and Microsoft.Data.SqlClient has SqlException. For the best level of error detail, catch these exceptions and use the members of these exception classes to get details of the error.
In addition to the provider-specific errors, .NET Framework data provider types can raise .NET Framework exceptions such as System.OutOfMemoryException and System.Threading.ThreadAbortException. Recovery from these exceptions may not be possible.
Bad input can cause a .NET Framework data provider type to raise an exception such as System.ArgumentException or System.IndexOutOfRangeException. Calling a method at the wrong time can raise System.InvalidOperationException.
So, in general, write an exception handler that catches any provider specific exceptions as well as exceptions from the common language runtime. These can be layered as follows:
```csharp
try {
// code here
}
catch (SqlException odbcEx) {
// Handle more specific SqlException exception here.
}
catch (Exception ex) {
// Handle generic ones here.
}
```
Or:
```csharp
try {
// code here
}
catch (Exception ex) {
if (ex is SqlException) {
// Handle more specific SqlException exception here.
}
else {
// Handle generic ones here.
}
}
```
It is also possible for a .NET Framework data provider method call to fail on a thread pool thread with no user code on the stack. In this case, and when using asynchronous method calls, you must register the event to handle those exceptions and avoid application crash.
## Examples
The following example generates a and then displays the exception.
[!code-csharp[SqlException_Errors1 Example#1](~/../sqlclient/doc/samples/SqlException_Errors1.cs#1)]
]]>
Gets the severity level of the error returned from the .NET Framework Data Provider for SQL Server.A value from 1 to 25 that indicates the severity level of the error.
remains open when the severity level is 19 or less. When the severity level is 20 or greater, the server ordinarily closes the . However, the user can reopen the connection and continue. In both cases, a is generated by the method executing the command.
For information about the warning and informational messages sent by SQL Server, see the Troubleshooting section of the SQL Server documentation.
This is a wrapper for the property of the first in the property.
If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `byte` is returned.
## Examples
The following example displays each within the collection.
[!code-csharp[SqlException_Errors2 Example#1](~/../sqlclient/doc/samples/SqlException_Errors2.cs#1)]
]]>
Represents the client connection ID. For more information, see Data Tracing in ADO.NET.The client connection ID.
.
]]>
Gets a collection of one or more objects that give detailed information about exceptions generated by the .NET Framework Data Provider for SQL Server.The collected instances of the class.
class always contains at least one instance of the class.
This is a wrapper for . For more information on SQL Server engine errors, see [Database Engine Events and Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors).
## Examples
The following example displays each within the collection.
[!code-csharp[SqlError_ToString Example#1](~/../sqlclient/doc/samples/SqlError_ToString.cs#1)]
]]>
Gets the line number within the Transact-SQL command batch or stored procedure that generated the error.The line number within the Transact-SQL command batch or stored procedure that generated the error.
property of the first in the property.
If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `int` is returned.
## Examples
The following example displays each within the collection.
[!code-csharp[SqlException_Errors2 Example#1](~/../sqlclient/doc/samples/SqlException_Errors2.cs#1)]
]]>
Gets a number that identifies the type of error.The number that identifies the type of error.
property of the first in the property.
If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `int` is returned.
For more information on SQL Server engine errors, see [Database Engine Events and Errors](/sql/relational-databases/errors-events/database-engine-events-and-errors).
## Examples
The following example displays each within the collection.
[!code-csharp[SqlException_Errors2 Example#1](~/../sqlclient/doc/samples/SqlException_Errors2.cs#1)]
]]>
Gets the name of the stored procedure or remote procedure call (RPC) that generated the error.The name of the stored procedure or RPC.
property of the first in the property.
If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `string` is returned.
## Examples
The following example displays each within the collection.
[!code-csharp[SqlException_Errors2 Example#1](~/../sqlclient/doc/samples/SqlException_Errors2.cs#1)]
]]>
Gets the name of the computer that is running an instance of SQL Server that generated the error.The name of the computer running an instance of SQL Server.
property of the first in the property.
If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `string` is returned.
## Examples
The following example displays each within the collection.
[!code-csharp[SqlException_Errors2 Example#1](~/../sqlclient/doc/samples/SqlException_Errors2.cs#1)]
]]>
Gets the name of the provider that generated the error.The name of the provider that generated the error.
property of the first in the property.
## Examples
The following example displays each within the collection.
[!code-csharp[SqlException_Errors2 Example#1](~/../sqlclient/doc/samples/SqlException_Errors2.cs#1)]
]]>
Gets a numeric error code from SQL Server that represents an error, warning or "no data found" message. For more information about how to decode these values, see Database Engine Events and Errors.The number representing the error code.
property of the first in the property.
If is `null`, the [`default`](https://docs.microsoft.com/dotnet/csharp/language-reference/builtin-types/default-values) value for `byte` is returned.
## Examples
The following example displays each within the collection.
[!code-csharp[SqlException_Errors2 Example#1](~/../sqlclient/doc/samples/SqlException_Errors2.cs#1)]
]]>
Returns a string that represents the current object, and includes the client connection ID (for more information, see ).A string that represents the current object..
, which includes the client connection ID:
```csharp
using Microsoft.Data.SqlClient;
using System;
public class A {
public static void Main() {
SqlConnection connection = new SqlConnection();
connection.ConnectionString = "Data Source=a_valid_server;Initial Catalog=Northwinda;Integrated Security=true";
try {
connection.Open();
}
catch (SqlException p) {
Console.WriteLine("{0}", p.ClientConnectionId);
Console.WriteLine("{0}", p.ToString());
}
connection.Close();
}
}
```
The following Visual Basic sample is functionally equivalent to the previous (C#) sample:
```vb
Imports Microsoft.Data.SqlClient
Imports System
Module Module1
Sub Main()
Dim connection As New SqlConnection()
connection.ConnectionString = "Data Source=a_valid_server;Initial Catalog=Northwinda;Integrated Security=true"
Try
connection.Open()
Catch p As SqlException
Console.WriteLine("{0}", p.ClientConnectionId)
Console.WriteLine("{0}", p.ToString())
End Try
connection.Close()
End Sub
End Module
```
]]>
Provides data for the event.
event contains a collection which contains the warnings sent from the server.
An event is generated when a SQL Server message with a severity level of 10 or less occurs.
]]>
Gets the collection of warnings sent from the server.The collection of warnings sent from the server.To be added.
Gets the full text of the error sent from the database.The full text of the error.
property of the first in the collection.
]]>
Gets the name of the object that generated the error.The name of the object that generated the error.
property of the first in the collection.
]]>
Retrieves a string representation of the event.A string representing the event.To be added.
The source of the event.A object that contains the event data.Represents the method that will handle the event of a .
delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event handler delegates, see [Handling and Raising Events](/dotnet/standard/events/).
]]>
Represents the set of arguments passed to the notification event handler.To be added.
value that indicates whether this notification is generated because of an actual change, or by the subscription.
value that indicates the reason for the notification event. This may occur because the data in the store actually changed, or the notification became invalid (for example, it timed out).
value that indicates the source that generated the notification.Creates a new instance of the object.To be added.
Gets a value that indicates the reason for the notification event, such as a row in the database being modified or a table being truncated.The notification event reason.
Gets a value that indicates the source that generated the notification, such as a change to the query data or the database's state.The source of the notification.To be added.
Gets a value that indicates whether this notification is generated because of an actual change, or by the subscription.A value indicating whether the notification was generated by a change or a subscription.To be added.
This enumeration provides additional information about the different notifications that can be received by the dependency event handler.
enumeration is referenced by an instance of the class.
]]>
The object already fired, and new commands cannot be added to it.
An underlying server object related to the query was modified.
Data was changed by a DELETE statement.
An underlying object related to the query was dropped.
An internal server error occurred.
The object has expired.
Data was changed by an INSERT statement.
A statement was provided that cannot be notified (for example, an UPDATE statement).
The statement was executed under an isolation mode that was not valid (for example, Snapshot).
Used to distinguish the server-side cause for a query notification firing.
The SET options were not set appropriately at subscription time.
A previous statement has caused query notifications to fire under the current transaction.
A SELECT statement that cannot be notified or was provided.
Fires as a result of server resource pressure.
The server was restarted (notifications are sent during restart.).
The subscribing query causes the number of templates on one of the target tables to exceed the maximum allowable limit.
One or more tables were truncated.
Used when the info option sent by the server was not recognized by the client.
Data was changed by an UPDATE statement.
Indicates the source of the notification received by the dependency event handler.
class.
Query notifications are supported only for SELECT statements that meet a list of specific requirements. For more information, see [SQL Server Service Broker](/sql/database-engine/configure-windows/sql-server-service-broker) and [Working with Query Notifications](/sql/connect/oledb/features/working-with-query-notifications).
]]>
A client-initiated notification occurred, such as a client-side time-out or as a result of attempting to add a command to a dependency that has already fired.
Data has changed; for example, an insert, update, delete, or truncate operation occurred.
The database state changed; for example, the database related to the query was dropped or detached.
The run-time environment was not compatible with notifications; for example, the isolation level was set to snapshot, or one or more SET options are not compatible.
A run-time error occurred during execution.
A database object changed; for example, an underlying object related to the query was dropped or modified.
Internal only; not intended to be used in your code.
The Transact-SQL statement is not valid for notifications; for example, a SELECT statement that could not be notified or a non-SELECT statement was executed.
A system-related event occurred. For example, there was an internal error, the server was restarted, or resource pressure caused the invalidation.
The subscription time-out expired.
Used when the source option sent by the server was not recognized by the client.
Describes the different notification types that can be received by an event handler through the parameter.
enumeration is referenced by an instance of the class. This information is provided when a notification event is fired with the class.
]]>
Data on the server being monitored changed. Use the item to determine the details of the change.
There was a failure to create a notification subscription. Use the object's item to determine the cause of the failure.
Used when the type option sent by the server was not recognized by the client.
Represents a parameter to a and optionally its mapping to columns. This class cannot be inherited. For more information on parameters, see [Configuring parameters](/sql/connect/ado-net/configure-parameters).
[!NOTE]
> Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server.
For more information, along with additional sample code demonstrating how to use parameters, see [Commands and Parameters](/sql/connect/ado-net/commands-parameters).
## Examples
The following example creates multiple instances of through the collection within the . These parameters are used to select data from the data source and put the data in the . This example assumes that a and a have already been created by using the appropriate schema, commands, and connection. For more information and additional examples on using parameters, see [Retrieving and Modifying Data in ADO.NET](/sql/connect/ado-net/retrieving-modifying-data) and [Configuring parameters](/sql/connect/ado-net/configure-parameters).
[!code-csharp[SqlParameterCollection_Add6](~/../sqlclient/doc/samples/SqlParameterCollection_Add6.cs#1)]
]]>
Initializes a new instance of the class.
and sets some of its properties.
[!code-csharp[SqlParameter_SqlParameter Example#1](~/../sqlclient/doc/samples/SqlParameter_SqlParameter.cs#1)]
]]>
The name of the parameter to map.One of the values.Initializes a new instance of the class that uses the parameter name and the data type.
are inferred from the value of the `dbType` parameter.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter_SqlParameter2 Example#1](~/../sqlclient/doc/samples/SqlParameter_SqlParameter2.cs#1)]
]]>
The value supplied in the parameter is an invalid back-end data type.
The name of the parameter to map.One of the values.The length of the parameter.Initializes a new instance of the class that uses the parameter name, the , and the size.
and sets some of its properties.
[!code-csharp[SqlParameter_SqlParameter4 Example#1](~/../sqlclient/doc/samples/SqlParameter_SqlParameter4.cs#1)]
]]>
The value supplied in the parameter is an invalid back-end data type.
The name of the parameter to map.One of the values.The length of the parameter.One of the values.
if the value of the field can be null; otherwise, .The total number of digits to the left and right of the decimal point to which is resolved.The total number of decimal places to which is resolved.The name of the source column () if this is used in a call to .One of the values.An that is the value of the .Initializes a new instance of the class that uses the parameter name, the type of the parameter, the size of the parameter, a , the precision of the parameter, the scale of the parameter, the source column, a to use, and the value of the parameter.
are inferred from the value of the `dbType` parameter if they are not explicitly set in the `size` and `precision` parameters.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter_SqlParameter1 Example#1](~/../sqlclient/doc/samples/SqlParameter_SqlParameter1.cs#1)]
]]>
The value supplied in the parameter is an invalid back-end data type.
The name of the parameter to map.One of the values.The length of the parameter.One of the values.The total number of digits to the left and right of the decimal point to which is resolved.The total number of decimal places to which is resolved.The name of the source column () if this is used in a call to >.One of the values.
if the source column is nullable; if it is not.An that is the value of the .The name of the database where the schema collection for this XML instance is located.The owning relational schema where the schema collection for this XML instance is located.The name of the schema collection for this parameter.Initializes a new instance of the class that uses the parameter name, the type of the parameter, the length of the parameter the direction, the precision, the scale, the name of the source column, one of the values, a Boolean for source column mapping, the value of the , the name of the database where the schema collection for this XML instance is located, the owning relational schema where the schema collection for this XML instance is located, and the name of the schema collection for this parameter.
and are inferred from the value of the `dbType` parameter if they are not explicitly set in the `size` and `precision` parameters.
]]>
The name of the parameter to map.One of the values.The length of the parameter.The name of the source column () if this is used in a call to >.Initializes a new instance of the class that uses the parameter name, the , the size, and the source column name.
and sets some of its properties.
[!code-csharp[SqlParameter_SqlParameter5 Example#1](~/../sqlclient/doc/samples/SqlParameter_SqlParameter5.cs#1)]
]]>
The value supplied in the parameter is an invalid back-end data type.
The name of the parameter to map.An that is the value of the .Initializes a new instance of the class that uses the parameter name and a value of the new .
in the `value` parameter, the is inferred from the Microsoft .NET Framework type of the .
Use caution when you use this overload of the constructor to specify integer parameter values. Because this overload takes a `value` of type , you must convert the integral value to an type when the value is zero, as the following C# example demonstrates.
```csharp
Parameter = new SqlParameter("@pname", (object)0);
```
If you do not perform this conversion, the compiler assumes that you are trying to call the constructor overload.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter_SqlParameter6 Example#1](~/../sqlclient/doc/samples/SqlParameter_SqlParameter6.cs#1)]
]]>
Gets or sets the object that defines how string comparisons should be performed for this parameter.A object that defines string comparison for this parameter.To be added.
Gets or sets the of the parameter.One of the values. The default is .
and are linked. Therefore, setting the changes the to a supporting .
For a list of the supported data types, see the appropriate member. For more information, see [DataAdapter Parameters](/sql/connect/ado-net/dataadapter-parameters).
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter_IsNullable Example#1](~/../sqlclient/doc/samples/SqlParameter_IsNullable.cs#1)]
]]>
Gets or sets a value that indicates whether the parameter is input-only, output-only, bidirectional, or a stored procedure return value parameter.One of the values. The default is .
is output, and execution of the associated does not return a value, the contains a null value.
`Output`, `InputOut`, and `ReturnValue` parameters returned by calling cannot be accessed until you close the .
## Examples
The following example creates a and sets some of its properties.
[Commands and Parameters](/sql/connect/ado-net/commands-parameters)
[DataAdapter Parameters](/sql/connect/ado-net/dataadapter-parameters)
[SQL Server and ADO.NET](/sql/connect/ado-net/sql/)
]]>
The property was not set to one of the valid values.
Enforces encryption of a parameter when using Always Encrypted. If SQL Server informs the driver that the parameter does not need to be encrypted, the query using the parameter will fail. This property provides additional protection against security attacks that involve a compromised SQL Server providing incorrect encryption metadata to the client, which may lead to data disclosure.
if the parameter has a force column encryption; otherwise, .To be added.
Gets or sets a value that indicates whether the parameter accepts null values. is not used to validate the parameter's value and will not prevent sending or receiving a null value when executing a command.
if null values are accepted; otherwise, . The default is .
class.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter#2](~/../sqlclient/doc/samples/SqlParameter.cs#2)]
]]>
Gets or sets the locale identifier that determines conventions and language for a particular region.The locale identifier associated with the parameter.
property.
```csharp
static void CreateSqlParameterLocaleId(){
SqlParameter parameter = new SqlParameter("pName", SqlDbType.VarChar);
parameter.LocaleId = 1033; // English - United States
}
```
]]>
Gets or sets the offset to the property.The offset to the . The default is 0.
and sets some of its properties.
[!code-csharp[SqlParameter#3](~/../sqlclient/doc/samples/SqlParameter.cs#3)]
]]>
Gets or sets the name of the .The name of the . The default is an empty string.
is specified in the form @paramname. You must set before executing a that relies on parameters.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter_ParameterName Example#1](~/../sqlclient/doc/samples/SqlParameter_ParameterName.cs#1)]
]]>
Gets or sets the maximum number of digits used to represent the property.The maximum number of digits used to represent the property. The default value is 0. This indicates that the data provider sets the precision for .
property is used by parameters that have a of `Decimal`.
You do not need to specify values for the and properties for input parameters, as they can be inferred from the parameter value. `Precision` and `Scale` are required for output parameters and for scenarios where you need to specify complete metadata for a parameter without indicating a value, such as specifying a null value with a specific precision and scale.
> [!NOTE]
> Use of this property to coerce data passed to the database is not supported. To round, truncate, or otherwise coerce data before passing it to the database, use the class that is part of the `System` namespace prior to assigning a value to the parameter's `Value` property.
> [!NOTE]
> Microsoft .NET Framework data providers that are included with the .NET Framework version 1.0 do not verify the or of parameter values. This can cause truncated data being inserted at the data source. If you are using .NET Framework version 1.0, validate the and of values before setting the parameter value. When you use .NET Framework version 1.1 or a later version, an exception is thrown if a parameter value is set with an invalid . values that exceed the parameter scale are still truncated.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter_Precision Example#1](~/../sqlclient/doc/samples/SqlParameter_Precision.cs#1)]
]]>
Gets or sets the number of decimal places to which is resolved.The number of decimal places to which is resolved. The default is 0.
property is used by parameters that have a of `Decimal`.
> [!WARNING]
> Data may be truncated if the property is not explicitly specified and the data on the server does not fit in scale 0 (the default).
You do not need to specify values for the and properties for input parameters, as they can be inferred from the parameter value. `Precision` and `Scale` are required for output parameters and for scenarios where you need to specify complete metadata for a parameter without indicating a value, such as specifying a null value with a specific precision and scale.
> [!NOTE]
> Use of this property to coerce data passed to the database is not supported. To round, truncate, or otherwise coerce data before passing it to the database, use the class that is part of the `System` namespace prior to assigning a value to the parameter's `Value` property.
> [!NOTE]
> .NET Framework data providers that are included with the .NET Framework version 1.0 do not verify the or of parameter values. This can cause truncated data to be inserted at the data source. If you are using .NET Framework version 1.0, validate the and of values before setting the parameter value. values that exceed the parameter scale are still truncated.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter#4](~/../sqlclient/doc/samples/SqlParameter.cs#4)]
]]>
Gets or sets the maximum size, in bytes, of the data within the column.The maximum size, in bytes, of the data within the column. The default value is inferred from the parameter value.
. For character types, the size specified with is in characters.
The property is used for binary and string types. For parameters of type `SqlType.String`, `Size` means length in Unicode characters. For parameters of type `SqlType.Xml`, `Size` is ignored.
For nonstring data types and ANSI string data, the property refers to the number of bytes. For Unicode string data, refers to the number of characters. The count for strings does not include the terminating character.
For variable-length data types, describes the maximum amount of data to transmit to the server. For example, for a Unicode string value, could be used to limit the amount of data sent to the server to the first one hundred characters.
If not explicitly set, the size is inferred from the actual size of the specified parameter value.
If the fractional part of the parameter value is greater than the size, then the value will be truncated to match the size.
For fixed length data types, the value of is ignored. It can be retrieved for informational purposes, and returns the maximum amount of bytes the provider uses when transmitting the value of the parameter to the server.
For information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter#5](~/../sqlclient/doc/samples/SqlParameter.cs#5)]
]]>
Gets or sets the name of the source column mapped to the and used for loading or returning the The name of the source column mapped to the . The default is an empty string.
is set to anything other than an empty string, the value of the parameter is retrieved from the column with the name. If is set to `Input`, the value is taken from the . If is set to `Output`, the value is taken from the data source. A of `InputOutput` is a combination of both.
For more information about how to use the property, see [DataAdapter Parameters](/sql/connect/ado-net/dataadapter-parameters) and [Updating Data Sources with DataAdapters](/sql/connect/ado-net/update-data-sources-with-dataadapters).
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter#6](~/../sqlclient/doc/samples/SqlParameter.cs#6)]
]]>
Sets or gets a value which indicates whether the source column is nullable. This allows to correctly generate Update statements for nullable columns.
if the source column is nullable; if it is not.
is used by the to correctly generate update commands when dealing with nullable columns. Generally, use of is limited to developers inheriting from .
uses this property to determine whether the source column is nullable, and sets this property to `true` if it is nullable, and `false` if it is not. When is generating its Update statement, it examines the for each parameter. If the property is `true`, generates a WHERE clauses like the following (in this query expression, "FieldName" represents the name of the field):
```
((@IsNull_FieldName = 1 AND FieldName IS NULL) OR
(FieldName = @Original_FieldName))
```
If for the field is false, generates the following WHERE clause:
```
FieldName = @OriginalFieldName
```
In addition, @IsNull_FieldName contains 1 if the source field contains null, and 0 if it does not. This mechanism allows for a performance optimization in SQL Server, and provides for common code that works across multiple providers.
]]>
Gets or sets the to use when you load One of the values. The default is .
used by the `DataRow.Item` property, or one of the `DataRow.GetChildRows` methods of the object.
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter#7](~/../sqlclient/doc/samples/SqlParameter.cs#7)]
]]>
Gets or sets the of the parameter.One of the values. The default is .
and are linked. Therefore, setting the changes the to a supporting .
For a list of the supported data types, see the appropriate member. For more information, see [DataAdapter Parameters](/sql/connect/ado-net/dataadapter-parameters).
For information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
]]>
Gets or sets the value of the parameter as an SQL type.An that is the value of the parameter, using SQL types. The default value is null.
that is sent to the server. For output and return value parameters, the value is set on completion of the and after the is closed.
This property can be set to null or . Use to send a NULL value as the value of the parameter. Use null or do not set to use the default value for the parameter.
If the application specifies the database type, the bound value is converted to that type when the provider sends the data to the server. The provider tries to convert any type of value if it supports the interface. Conversion errors may result if the specified type is not compatible with the value.
Both the and properties can be inferred by setting the .
The property is overwritten by `SqlDataAdapter.UpdateCommand`.
Use the property to return parameter values as common language runtime (CLR) types.
For information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
]]>
Gets or sets the type name for a table-valued parameter.The type name of the specified table-valued parameter.To be added.
Gets or sets a that represents a user-defined type as a parameter.A that represents the fully qualified name of a user-defined type in the database.
, see [Retrieving UDT Data](https://msdn.microsoft.com/library/ms131080.aspx).
]]>
Gets or sets the value of the parameter.An that is the value of the parameter. The default value is null.
that is sent to the server. For output and return value parameters, the value is set on completion of the and after the is closed.
This property can be set to `null` or . Use to send a NULL value as the value of the parameter. Use `null` or do not set to use the default value for the parameter.
An exception is thrown if non-Unicode XML data is passed as a string.
If the application specifies the database type, the bound value is converted to that type when the provider sends the data to the server. The provider tries to convert any type of value if it supports the interface. Conversion errors may result if the specified type is not compatible with the value.
Both the and properties can be inferred by setting the Value.
The property is overwritten by `SqlDataAdapter.UpdateCommand`.
For information about streaming, see [SqlClient Streaming Support](/sql/connect/ado-net/sqlclient-streaming-support).
## Examples
The following example creates a and sets some of its properties.
[!code-csharp[SqlParameter#8](~/../sqlclient/doc/samples/SqlParameter.cs#8)]
]]>
Gets the name of the database where the schema collection for this XML instance is located.The name of the database where the schema collection for this XML instance is located.
and are also null.
]]>
Gets the name of the schema collection for this XML instance.The name of the schema collection for this XML instance.
and are also null.
]]>
The owning relational schema where the schema collection for this XML instance is located.The owning relational schema for this XML instance.
and are also null.
]]>
Resets the type associated with this .
and properties of the .
]]>
Resets the type associated with this .
and properties of the .
]]>
Gets a string that contains the .A string that contains the .To be added.
Represents a collection of parameters associated with a and their respective mappings to columns in a . This class cannot be inherited.
through the collection. The parameters are used to select data within the data source and populate the . This code assumes that a and a have already been created with the appropriate schema, commands, and connection.
[!code-csharp[SqlParameterCollection_Add6 Example#1](~/../sqlclient/doc/samples/SqlParameterCollection_Add6.cs#1)]
]]>
Returns an Integer that contains the number of elements in the . Read-only.The number of elements in the as an Integer.To be added.
Gets a value that indicates whether the has a fixed size.
if the has a fixed size; otherwise, .To be added.
Gets a value that indicates whether the is read-only.
if the is read-only; otherwise, .To be added.
The zero-based index of the parameter to retrieve.Gets the at the specified index.The at the specified index.
objects to supply an input parameter to a stored procedure that returns results in an output parameter. The code iterates through the items in the and displays some parameter properties in the console window. This example assumes a valid connection string to the **AdventureWorks** sample database on an instance of SQL Server.
[!code-csharp[SqlParameterCollection_Count Example#1](~/../sqlclient/doc/samples/SqlParameterCollection_Count.cs#1)]
]]>
The specified index does not exist.
The name of the parameter to retrieve.Gets the with the specified name.The with the specified name.
. If the `parameterName` is not valid, an will be thrown.
]]>
The specified is not valid.
Gets an object that can be used to synchronize access to the .An object that can be used to synchronize access to the .To be added.
The to add to the collection.Adds the specified object to the .A new object.
The specified in the parameter is already added to this or another .The parameter passed was not a .The parameter is null.
An .Adds the specified object to the .The index of the new object.To be added.
The name of the parameter.One of the values.Adds a to the given the parameter name and the data type.A new object.
The name of the parameter.The of the to add to the collection.The size as an .Adds a to the , given the specified parameter name, and size.A new object.
The name of the parameter.One of the values.The column length.The name of the source column () if this is used in a call to .Adds a to the with the parameter name, the data type, and the column length.A new object.
The values to add.Adds an array of values to the end of the .To be added.
The values to add.Adds an array of values to the end of the .To be added.
The name of the parameter.The value to be added. Use instead of null, to indicate a null value.Adds a value to the end of the .A object.
replaces the `SqlParameterCollection.Add` method that takes a and an . The overload of `Add` that takes a string and an object was deprecated because of possible ambiguity with the `SqlParameterCollection.Add` overload that takes a and a enumeration value where passing an integer with the string could be interpreted as being either the parameter value or the corresponding value. Use whenever you want to add a parameter by specifying its name and value.
For `Xml` enumeration values, you can use a string, an XML value, an derived type instance, or a object.
## Examples
The following example demonstrates how to use the `AddWithValue` method.
[!code-csharp[SqlParameterCollection_AddWithValue#1](~/../sqlclient/doc/samples/SqlParameterCollection_AddWithValue.cs#1)]
]]>
Removes all the objects from the .To be added.
The value.Determines whether the specified is in this .
if the contains the value; otherwise, .To be added.
The value.Determines whether the specified is in this .
if the contains the value; otherwise, .To be added.
The value.Determines whether the specified parameter name is in this .
if the contains the value; otherwise, .To be added.
The one-dimensional that is the destination of the elements copied from the current .A 32-bit integer that represents the index in the at which copying starts.Copies all the elements of the current to the specified one-dimensional starting at the specified destination index.To be added.
The that is the destination of the elements copied from the current .A 32-bit integer that represents the index in the at which copying starts.Copies all the elements of the current to the specified starting at the specified destination index.To be added.
Returns an enumerator that iterates through the .An for the .To be added.
To be added.To be added.To be added.To be added.
To be added.To be added.To be added.To be added.
The to find.Gets the location of the specified within the collection.The zero-based location of the specified that is a within the collection. Returns -1 when the object does not exist in the .To be added.
The to find.Gets the location of the specified within the collection.The zero-based location of the specified that is a within the collection. Returns -1 when the object does not exist in the .To be added.
The case-sensitive name of the to find.Gets the location of the specified with the specified name.The zero-based location of the specified with the specified case-sensitive name. Returns -1 when the object does not exist in the .To be added.
The zero-based index at which value should be inserted.A object to be inserted in the .Inserts a object into the at the specified index.To be added.
The zero-based index at which value should be inserted.An to be inserted in the .Inserts an into the at the specified index.To be added.
A object to remove from the collection.Removes the specified from the collection.
object in a collection. If the parameter exists, the example removes it. This example assumes that a collection has already been created by a .
[!code-csharp[SqlParameterCollection_Remove Example#1](~/../sqlclient/doc/samples/SqlParameterCollection_Remove.cs#1)]
]]>
The parameter is not a .The parameter does not exist in the collection.
The object to remove from the collection.Removes the specified from the collection.To be added.
The zero-based index of the object to remove.Removes the from the at the specified index.To be added.
The name of the to remove.Removes the from the at the specified parameter name.To be added.
To be added.To be added.To be added.To be added.
To be added.To be added.To be added.To be added.
Represents the set of arguments passed to the .To be added.
An that indicates the number of rows copied during the current bulk copy operation.Creates a new instance of the object.
Gets or sets a value that indicates whether the bulk copy operation should be aborted.
if the bulk copy operation should be aborted; otherwise .
property to cancel a bulk copy operation. Set to `true` to abort the bulk copy operation.
If you call the **Close** method from , an exception is generated, and the object state does not change.
If an application specifically creates a object in the constructor, the transaction is not rolled back. The application is responsible for determining whether it is required to rollback the operation, and if so, it must call the method. If the application does not create a transaction, the internal transaction corresponding to the current batch is automatically rolled back. However, changes related to previous batches within the bulk copy operation are retained, because the transactions for them already have been committed.
]]>
Gets a value that returns the number of rows copied during the current bulk copy operation.
that returns the number of rows copied.
property is reset on each call to any of the `SqlBulkCopy.WriteToServer` methods.
]]>
The source of the event.A object that contains the event data.Represents the method that handles the event of a .To be added.
Provides data for the event.
event is raised when an to a row is completed.
When using , there are two events that occur for each data row updated. The order of execution is as follows:
1. The values in the are moved to the parameter values.
2. The event is raised.
3. The command executes.
4. If the command is set to `FirstReturnedRecord`, and the first returned result is placed in the .
5. If there are output parameters, they are placed in the .
6. The event is raised.
7. is called.
## Examples
The following example shows how to use both the and events.
The event returns this output:
Event Arguments: (command=Microsoft.Data.SqlClient.SqlCommand commandType=2 status=0)
The event returns this output:
Event Arguments: (command=Microsoft.Data.SqlClient.SqlCommand commandType=2 recordsAffected=1 row=System.Data.DataRow[37] status=0)
[!code-csharp[SqlDataAdapter_RowUpdated Example#1](~/../sqlclient/doc/samples/SqlDataAdapter_RowUpdated.cs#1)]
]]>
The sent through an .The executed when is called.One of the values that specifies the type of query executed.The sent through an .Initializes a new instance of the class.To be added.
Gets or sets the executed when is called.The executed when is called.To be added.
The source of the event.The that contains the event data.Represents the method that will handle the event of a .
delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event handler delegates, see [Handling and Raising Events](/dotnet/standard/events/).
]]>
Provides data for the event.
event is raised before an to a row.
When you are using , there are two events that occur for each data row updated. The order of execution is as follows:
1. The values in the are moved to the parameter values.
2. The event is raised.
3. The command executes.
4. If the command is set to `FirstReturnedRecord`, and the first returned result is placed in the .
5. If there are output parameters, they are placed in the .
6. The event is raised.
7. is called.
## Examples
The following example shows how to use both the and events.
The event returns this output:
event args: (command=Microsoft.Data.SqlClient.SQLCommand commandType=2 status=0)
The event returns this output:
event args: (command=Microsoft.Data.SqlClient.SQLCommand commandType=2 recordsAffected=1 row=System.Data.DataRow[37] status=0)
[!code-csharp[SqlRowUpdatingEventArgs Example#1](~/../sqlclient/doc/samples/SqlRowUpdatingEventArgs.cs#1)]
]]>
The to .The to execute during .One of the values that specifies the type of query executed.The sent through an .Initializes a new instance of the class.To be added.
To be added.To be added.To be added.
Gets or sets the to execute when performing the .The to execute when performing the .To be added.
The source of the event.The that contains the event data.Represents the method that will handle the event of a .
to influence the processing of the updates. For example, the handler may opt to skip the update of the current row or skip the update of all remaining rows. Note that the rows are updated in the order that they were received from the data source.
When you create a delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event handler delegates, see [Handling and Raising Events](/dotnet/standard/events/).
]]>
Represents a Transact-SQL transaction to be made in a SQL Server database. This class cannot be inherited.
object by calling on the object. All subsequent operations associated with the transaction (for example, committing or aborting the transaction), are performed on the object.
> [!NOTE]
> `Try`/`Catch` exception handling should always be used when committing or rolling back a . Both and generate an if the connection is terminated or if the transaction has already been rolled back on the server.
For more information on SQL Server transactions, see [Explicit Transactions](https://msdn.microsoft.com/library/ms175127\(SQL.105\).aspx) and [Coding Efficient Transactions](https://msdn.microsoft.com/library/ms187484\(SQL.105\).aspx).
## Examples
The following example creates a and a . It also demonstrates how to use the , , and methods. The transaction is rolled back on any error, or if it is disposed without first being committed. `Try`/`Catch` error handling is used to handle any errors when attempting to commit or roll back the transaction.
[!code-csharp[SqlConnection_BeginTransaction Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction.cs#1)]
]]>
Gets the object associated with the transaction, or if the transaction is no longer valid.The object associated with the transaction.
.
]]>
To be added.To be added.To be added.
Specifies the for this transaction.The for this transaction. The default is .
applies to the whole transaction.
For more information on SQL Server isolation levels, see [Transaction Isolation Levels](/sql/t-sql/language-elements/transaction-isolation-levels).
]]>
Commits the database transaction.
method is equivalent to the Transact-SQL COMMIT TRANSACTION statement. You cannot roll back a transaction once it has been committed, because all modifications have become a permanent part of the database. For more information, see [COMMIT TRANSACTION (Transact-SQL)](/sql/t-sql/language-elements/commit-transaction-transact-sql).
> [!NOTE]
> `Try`/`Catch` exception handling should always be used when committing or rolling back a . Both `Commit` and generates an if the connection is terminated or if the transaction has already been rolled back on the server.
For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql).
## Examples
The following example creates a and a . It also demonstrates how to use the , , and methods. The transaction is rolled back on any error. `Try`/`Catch` error handling is used to handle any errors when attempting to commit or roll back the transaction.
[!code-csharp[SqlConnection_BeginTransaction Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction.cs#1)]
]]>
An error occurred while trying to commit the transaction.The transaction has already been committed or rolled back.
-or-
The connection is broken.
to release managed and unmanaged resources; to release only unmanaged resources.Releases the unmanaged resources used and optionally releases the managed resources.
.
]]>
Rolls back a transaction from a pending state.
Rolls back a transaction from a pending state.
method is equivalent to the Transact-SQL ROLLBACK TRANSACTION statement. For more information, see [ROLLBACK TRANSACTION (Transact-SQL)
](/sql/t-sql/language-elements/rollback-transaction-transact-sql).
The transaction can only be rolled back from a pending state (after has been called, but before is called). The transaction is rolled back in the event it is disposed before `Commit` or `Rollback` is called.
> [!NOTE]
> `Try`/`Catch` exception handling should always be used when rolling back a transaction. A `Rollback` generates an if the connection is terminated or if the transaction has already been rolled back on the server.
For more information on SQL Server transactions, see [Transactions (Transact-SQL)](/sql/t-sql/language-elements/transactions-transact-sql).
## Examples
The following example creates a and a . It also demonstrates how to use the , , and methods. The transaction is rolled back on any error. `Try`/`Catch` error handling is used to handle any errors when attempting to commit or roll back the transaction.
[!code-csharp[SqlConnection_BeginTransaction Example#1](~/../sqlclient/doc/samples/SqlConnection_BeginTransaction.cs#1)]
]]>
An error occurred while trying to commit the transaction.The transaction has already been committed or rolled back.
-or-
The connection is broken.
The name of the savepoint.Creates a savepoint in the transaction that can be used to roll back a part of the transaction, and specifies the savepoint name.
method is equivalent to the Transact-SQL SAVE TRANSACTION statement.
The value used in the `savePoint` parameter can be the same value used in the `transactionName` parameter of some implementations of the method.
Savepoints offer a mechanism to roll back parts of transactions. You create a savepoint using the method, and then later call the method to roll back to the savepoint instead of rolling back to the start of the transaction.
]]>
An error occurred while trying to commit the transaction.The transaction has already been committed or rolled back.
-or-
The connection is broken.
Represents the set of arguments passed to the event.
The current retry attempt count.The delay that indicates how long the current thread will be suspended before the next iteration is invoked.The list of exceptions since the first retry that caused the retry logic to re-execute the function.Initializes a new instance of the class.
Retry-attempt-number, after the first exception occurrence.
that returns the number of retry execution attempts; starting from 1.
Gets the current waiting time as a object.
The upcoming gap time before the next execution attempt.
Gets or sets a value that indicates whether the retry logic should be canceled. If set to , the execution attempt will be interrupted immediately.
Gets the list of exceptions since the first attempt failure.List of occurred exceptions.
Generates a sequence of time intervals.
The default gap time of each interval.
The maximum allowed time interval value.
The minimum allowed time interval value.
Gets the element in the collection at the current position of the enumerator.
Initializes a new instance of the class with a default value of zero for the gap time, minimum, and maximum interval time.
The gap time used to calculate the time delay before each attempt.The maximum time allowed as a gap time.The minimum time allowed as a gap time.Initializes a new instance of the class.The supplied arguments failed validation.
Sets the enumerator to its initial position, which is before the first element in the collection.
The gap time of each interval. Must be between 0 and 120 seconds.Maximum time interval value. Must be between 0 and 120 seconds.Minimum time interval value. Must be less than maximum time interval and between 0 and 120 seconds.Validate the enumeration parameters.The supplied arguments failed validation.
Calculates the next interval time.Returns the next gap time interval.
Advances the enumerator to the next element of the collection.Returns , if the enumerator was successfully advanced to the next element; if the enumerator has passed the end of the collection.
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
Creates a new object that is a copy of the current instance.A new object that is a copy of this instance.
Retrieves the next time interval with respect to the number of retries if a transient condition occurs.
Maximum number of retries.
that returns the maximum number of retry execution attempts that will be attempted after the first failure.
Current retry number starting from zero.
that returns the number of retry execution attempts after the first failure.
The timer interval enumerator.
value that indicates an enumerator to generate a sequence of time intervals.
Delegate to a transient condition predicate. The function that this delegate points to must return a true value when an expected transient exception happens.
value that delegates to a function that receives a input parameter.
The sender object.Pre-retry validation for the sender state.Returns if the sender is authorized to retry the operation.
[IMPORTANT!]
> Operations that are part of a **Transaction** are not safe to retry without specific knowledge of business logic. Due to this complexity, retry logic should be managed at the application level.
> [!NOTE]
> The `RetryCondition` is an extra condition that checks before executing the `TransientPredicate` and the default condition always returns **true**.
]]>
The interval time that is generated by the `RetryIntervalEnumerator`.Try to get the next interval time by using the enumerator if the counter does not exceed the number of retries.Returns if the number of retry attempts has not been exceeded; otherwise .
Set the counters and enumerator to default values for next use.
Creates a new object that is a copy of the current instance.When implemented in a derived class, the method is expected to return a new object of the current instance. The default implementation throws NotImplementedException.In all cases.
Applies retry logic on an operation through the `Execute` or `ExecuteAsync` function.
Occurs before applying the calculated delay time and executing the function on a next attempt.
with event argument of object can be subscribed.
[IMPORTANT!]
> Don't block execution with a time consuming action when an event occurs. For instance, if you log data to a file, run it in a new thread to avoid blocking the main execution thread.
]]>
Defines the retry logic used to decide when to retry based on the encountered exception.
[!NOTE]
> The `RetryLogic` property is assigned at `SqlRetryLogicBaseProvider` creation and its value is used as a template internally. Don't use it to monitor the status of the retry logic during and after execution. Instead, use the event to collect data about retry executions.
]]>
The object that the `function` returns when executed.The source of the event.The operation to re-execute if a transient condition occurs.Executes a function and applies retry logic, if enabled. **Note:** Exceptions will be reported via an aggregate exception if the execution isn't successful via retry attempts.
The return value of the `function` if it runs without exception.
[!NOTE]
> The type of exception depends on the `function`'s internal implementation. But if the exception is due to all retry attempts failing, it will be an that consists of all exceptions that happened during the failed attempts.
]]>
The `function` parameter can't be `null`.The collection of exceptions after all retry attempts have failed.
The object that the `function` returns in a Task when executed.The source of the event.The operation to re-execute if a transient condition occurs.The cancellation instruction.Executes a function and applies retry logic, if enabled. The cancellation token can be used to request that the operation be abandoned before the execution attempts are exceeded. **Note:** Exceptions will be reported via the returned Task object, which will contain an aggregate exception if execution fails for all retry attempts.A task representing the asynchronous operation. The results of the task will be the return value of the `function`, if it runs without exception.
[!NOTE]
> If the exception comes from all retry attempts failing, it will be an that consists of all exceptions from the failed attempts.
]]>
The `function` parameter can't be `null`.The collection of exceptions after failed retry attempts.
The source of the event.The operation to re-execute if a transient condition occurs.The cancellation instruction.Executes a function and applies retry logic, if enabled. The cancellation token can be used to request that the operation be abandoned before the execution attempts are exceeded. **Note:** Exceptions will be reported via the returned Task object, which will contain an aggregate exception if execution fails for all retry attempts.A Task or an exception.
[!NOTE]
> If the exception comes from all retry attempts failing, it will be an that consists of all exceptions from the failed attempts.
]]>
The `function` parameter can't be `null`.The collection of exceptions after failed retry attempts.
Provides the retry logic parameters to create an instance of the class by using methods.
Sets the number of times to try and execute the function.
between 1 and 60; 1 means to execute one time and if an error is encountered, don't retry.
Sets the gap time interval as a object.
The upcoming gap time before the next execution attempt; must be between 0 and 120 seconds.
Sets the minimum allowed gap time interval as a object.
The minimum upcoming gap time before the next execution attempt; the default value is **zero** and must be between 0 and 120 seconds.
Sets the allowed maximum gap time interval as a object.
The maximum upcoming gap time interval before the next execution attempt; must be between 0 and 120 seconds.
Sets the list of transient error numbers on which to retry when they occur.List of ; Set to to use the internal list of exceptions from the object.
Sets a pre-retry validation function on the to only include specific SQL statements.
The pre-retry validation delegate function; if the `CommandText` is authorized to retry the operation.
Provides different retry logic providers with a common list of transient errors.
An object of containing the configuration for the object.Provides an exponential time interval retry logic provider.A object.
[!NOTE]
> The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time.
]]>
If the `retryLogicOption` parameter was null.If at least one of the following conditions occurs:
- `NumberOfTries` is less than 1 or bigger than 60.
- `DeltaTime` is bigger than 120 seconds.
- `MinTimeInterval` is bigger than 120 seconds.
- `MaxTimeInterval` is bigger than 120 seconds.
- `MinTimeInterval` is not less than `MaxTimeInterval`.
An object of containing the configuration for the object.Provides an incremental time interval retry logic provider.A object.
[!NOTE]
> The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time.
]]>
If the `retryLogicOption` parameter was null.If at least one of the following conditions occurs:
- `NumberOfTries` is less than 1 or bigger than 60.
- `DeltaTime` is bigger than 120 seconds.
- `MinTimeInterval` is bigger than 120 seconds.
- `MaxTimeInterval` is bigger than 120 seconds.
- `MinTimeInterval` is not less than `MaxTimeInterval`.
An object of containing the configuration for the object.Provides a fixed interval time retry logic provider.A object.
[!NOTE]
> The inner enumerator includes randomization to prevent multiple instances of the client from performing subsequent retry attempts at the same time.
]]>
If the `retryLogicOption` parameter was null.If at least one of the following conditions occurs:
- `NumberOfTries` is less than 1 or bigger than 60.
- `DeltaTime` is bigger than 120 seconds.
- `MinTimeInterval` is bigger than 120 seconds.
- `MaxTimeInterval` is bigger than 120 seconds.
- `MinTimeInterval` is not less than `MaxTimeInterval`.
Provides a non-retriable provider with a that returns .A object.
[!NOTE]
> The returned provider of this function performs a single execution without any retry logic.
]]>
Represents a single row of data and its metadata.
to send result sets to the client from managed code stored-procedures.
When writing common language runtime (CLR) applications, you should re-use existing `SqlDataRecord` objects instead of creating new ones every time. Creating many new `SqlDataRecord` objects could severely deplete memory and adversely affect performance.
## Examples
The following example shows how to create several objects, which describe the column metadata of a record, and creating a . The column values of the are set and the is sent to the calling program by using the class.
[!code-csharp[SqlDataRecord Samples#1](~/../sqlclient/doc/samples/SqlDataRecord.cs#1)]
]]>
An array of objects that describe each column in the .Inititializes a new instance with the schema based on the array of objects passed as an argument.
object from two objects, which indicate the column name and data type.
[!code-csharp[SqlDataRecord Samples#2](~/../sqlclient/doc/samples/SqlDataRecord.cs#2)]
]]>
The is .
Gets the number of columns in the data row. This property is read-only.The number of columns in the data row as an integer.To be added.
The zero-based ordinal of the column.Gets the common language runtime (CLR) type value for the column specified by the column argument.The CLR type value of the column specified by the .
is returned.
]]>
The is less than 0 or greater than the number of columns (that is, ).
The name of the column.Gets the common language runtime (CLR) type value for the column specified by the column argument.The CLR type value of the column specified by the .
is returned.
]]>
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based ordinal of the column.The offset into the field value to start retrieving bytes.The target buffer to which to copy bytes.The offset into the buffer to which to start copying bytes.The number of bytes to copy to the buffer.Gets the value for the column specified by the ordinal as an array of objects.The number of bytes copied.
repeatedly, adjusting the `fieldOffset` parameter accordingly in each call.
]]>
The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based ordinal of the column.The offset into the field value to start retrieving characters.The target buffer to copy chars to.The offset into the buffer to start copying chars to.The number of chars to copy to the buffer.Gets the value for the column specified by the ordinal as an array of objects.The number of characters copied.
repeatedly adjusting the `fieldOffset` parameter accordingly in each call.
]]>
The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
To be added.To be added.To be added.To be added.
The zero-based ordinal of the column.Returns the name of the data type for the column specified by the ordinal argument.A that contains the data type of the column.
The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based column ordinal.Returns the specified column's data as a .The value of the specified column as a .To be added.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based ordinal of the column.Returns a object representing the common language runtime (CLR) type that maps to the SQL Server type of the column specified by the argument.The column type as a object.To be added.The is less than 0 or greater than the number of columns (that is, ).The column is of a user-defined type that is not available to the calling application domain.The column is of a user-defined type that is not available to the calling application domain.There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).The column specified by is null.There is a type mismatch.
The zero-based ordinal of the column.Returns the name of the column specified by the ordinal argument.A containing the column name.To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The name of the column to look up.Returns the column ordinal specified by the column name.The zero-based ordinal of the column as an integer.To be added.
is .The column name could not be found.There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Returns a object that represents the type (as a SQL Server type, defined in ) that maps to the SQL Server type of the column.The column type as a object.To be added.The is less than 0 or greater than the number of columns (that is, ).The column is of a user-defined type that is not available to the calling application domain.The column is of a user-defined type that is not available to the calling application domain.There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Returns a object, describing the metadata of the column specified by the column ordinal.The column metadata as a object.To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Returns the data value stored in the column, expressed as a SQL Server type, specified by the column ordinal.The value of the column, expressed as a SQL Server type, as a .
property is true.
]]>
The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The array into which to copy the values column values.Returns the values for all the columns in the record, expressed as SQL Server types, in an array.An that indicates the number of columns copied.
property is true.
The length of the `values` array does not need to match the number of columns in the record. If the array length is greater than the number of columns, all of the column values are copied into the array; if it is less, only the array length number of column values are copied into the array, starting at the column value with ordinal 0.
]]>
is .There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based ordinal of the column.Gets the value for the column specified by the ordinal as a .The column value as a .To be added.The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The zero-based column ordinal.Returns the specified column's data as a .The value of the specified column as a .To be added.
The zero-based ordinal of the column.Returns the common language runtime (CLR) type value for the column specified by the ordinal argument.The CLR type value of the column specified by the ordinal.
is returned.
]]>
The is less than 0 or greater than the number of columns (that is, ).There is a type mismatch.
The array into which to copy the values column values.Returns the values for all the columns in the record, expressed as common language runtime (CLR) types, in an array.An that indicates the number of columns copied.
is returned.
The length of the `values` array does not need to match the number of columns in the record. If the array length is greater than the number of columns, all of the column values are copied into the array; if it is less, only the array length number of column values is copied into the array, starting at the column value with ordinal 0.
]]>
is .There is a type mismatch.
The zero-based ordinal of the column.Returns true if the column specified by the column ordinal parameter is null.
if the column is null; otherwise.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The offset into the field value to start copying bytes.The target buffer from which to copy bytes.The offset into the buffer from which to start copying bytes.The number of bytes to copy from the buffer.Sets the data stored in the column to the specified array of values.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The offset into the field value to start copying characters.The target buffer from which to copy chars.The offset into the buffer from which to start copying chars.The number of chars to copy from the buffer.Sets the data stored in the column to the specified array of values.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the value of the column specified to the value.To be added.
The zero-based ordinal of the column.Sets the value in the specified column to .To be added.
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the data stored in the column to the specified value.To be added.The is less than 0 or greater than the number of columns (that is, ).
The zero-based ordinal of the column.The new value of the column.Sets the value of the column specified to the .To be added.The passed in is a negative number.The value passed in is greater than 24 hours in length.
The zero-based ordinal of the column.The new value for the specified column.Sets a new value, expressed as a common language runtime (CLR) type, for the column specified by the column ordinal.
instance.
]]>
The is less than 0 or greater than the number of columns (that is, ).
The array of new values, expressed as CLR types boxed as references, for the instance.Sets new values for all of the columns in the . These values are expressed as common language runtime (CLR) types.The number of column values set as an integer.
instance.
]]>
is .The size of values does not match the number of columns in the instance.
Specifies and retrieves metadata information from parameters and columns of objects. This class cannot be inherited.
objects, which describe the column metadata of a record, and the creation of a . The column values of the are set and the is sent to the calling program using the class.
[!code-csharp[SqlMetaData Samples#1](~/../sqlclient/doc/samples/SqlMetaData.cs#1)]
]]>
The name of the column.The SQL Server type of the parameter or column.Initializes a new instance of the class with the specified column name and type.
, , , and properties are set to `null`):
|SqlDbType|Maximum length|Precision|Scale|Locale|Compare options|
|---------------|--------------------|---------------|-----------|------------|---------------------|
|`Bit`|1|1|0|0|None|
|`BigInt`|8|19|0|0|None|
|`DateTime`|8|23|3|0|None|
|`Decimal`|9|18|0|0|None|
|`Float`|8|53|0|0|None|
|`Int`|4|10|0|0|None|
|`Money`|8|19|4|0|None|
|`Numeric`|9|18|0|0|None|
|`SmallDateTime`|4|16|0|0|None|
|`SmallInt`|2|5|0|0|None|
|`SmallMoney`|4|10|4|0|None|
|`TimeStamp`|8|0|0|0|None|
|`TinyInt`|1|3|0|0|None|
|`UniqueIdentifier`|16|0|0|0|None|
|`Xml`|Max (-1)|0|0|0|IgnoreCase, IgnoreKanaType, IgnoreWidth|
## Examples
The following example creates a new object by specifying the column name and a column data type of .`Int`.
[!code-csharp[SqlMetaData Samples#3](~/../sqlclient/doc/samples/SqlMetaData.cs#3)]
]]>
The is .A that is not allowed was passed to the constructor as .
The name of the column.The SQL Server type of the parameter or column.Specifies whether this column should use the default server value.Specifies if the column in the table-valued parameter is unique.Specifies the sort order for a column.Specifies the ordinal of the sort column.Initializes a new instance of the class with the specified column name, and default server. This form of the constructor supports table-valued parameters by allowing you to specify if the column is unique in the table-valued parameter, the sort order for the column, and the ordinal of the sort column.
The name of the parameter or column.The SQL Server type of the parameter or column.The precision of the parameter or column.The scale of the parameter or column.Initializes a new instance of the class with the specified column name, type, precision, and scale.
, , , and properties are set to `null`):
|SqlDbType|Maximum length|Precision|Scale|Locale|Compare options|
|---------------|--------------------|---------------|-----------|------------|---------------------|
|Decimal|9|18|0|0|None|
]]>
The is .A that is not allowed was passed to the constructor as , or was greater than .
The name of the column.The SQL Server type of the parameter or column.The precision of the parameter or column.The scale of the parameter or column.Specifies whether this column should use the default server value.Specifies if the column in the table-valued parameter is unique.Specifies the sort order for a column.Specifies the ordinal of the sort column.Initializes a new instance of the class with the specified column name, type, precision, scale, and server default. This form of the constructor supports table-valued parameters by allowing you to specify if the column is unique in the table-valued parameter, the sort order for the column, and the ordinal of the sort column.
The name of the column.The SQL Server type of the parameter or column.The maximum length of the specified type.Initializes a new instance of the class with the specified column name, type, and maximum length.
, or -1 is allowed for a `dbType` of `Text`, `NText`, or `Image`.
For a `dbType` of `Varchar`, `Nvarchar`, or `VarBinary`, a length specification of , or -1, declares the metadata as varchar(max), nvarchar(max), or nvarbinary(max), respectively.
The following are the default values assigned to `dbType`, depending on the `SqlDbType` (the , , , and properties are set to `null`):
|SqlDbType|Precision|Scale|Locale|Compare options|
|---------------|---------------|-----------|------------|---------------------|
|Binary|0|0|0|IgnoreCase, IgnoreKanaType, IgnoreWidth|
|Char|0|0|\|IgnoreCase, IgnoreKanaType, IgnoreWidth|
|Image|0|0|0|None|
|NChar|0|0|\|IgnoreCase, IgnoreKanaType, IgnoreWidth|
|NText|0|0|\|IgnoreCase, IgnoreKanaType, IgnoreWidth|
|NVarChar|0|0|\|IgnoreCase, IgnoreKanaType, IgnoreWidth|
|Text|0|0|\|IgnoreCase, IgnoreKanaType, IgnoreWidth|
|VarBinary|0|0||IgnoreCase, IgnoreKanaType, IgnoreWidth|
|VarChar|0|0|\|IgnoreCase, IgnoreKanaType, IgnoreWidth|
## Examples
The following example creates a new object by specifying the column name, a column data type of `.NVarChar`, and a maximum length of 12 characters.
[!code-csharp[SqlMetaData Samples#2](~/../sqlclient/doc/samples/SqlMetaData.cs#2)]
]]>
The is .A SqlDbType that is not allowed was passed to the constructor as .
The name of the column.The SQL Server type of the parameter or column.The maximum length of the specified type.Specifies whether this column should use the default server value.Specifies if the column in the table-valued parameter is unique.Specifies the sort order for a column.Specifies the ordinal of the sort column.Initializes a new instance of the class with the specified column name, type, maximum length, and server default. This form of the constructor supports table-valued parameters by allowing you to specify if the column is unique in the table-valued parameter, the sort order for the column, and the ordinal of the sort column.
The name of the column.The SQL Server type of the parameter or column.The maximum length of the specified type.The precision of the parameter or column.The scale of the parameter or column.The locale ID of the parameter or column.The comparison rules of the parameter or column.A instance that points to the UDT.Initializes a new instance of the class with the specified column name, type, maximum length, precision, scale, locale ID, compare options, and user-defined type (UDT).
, , , and properties are set to `null`):
|SqlDbType|Maximum length|Precision|Scale|Locale|Compare options|
|---------------|--------------------|---------------|-----------|------------|---------------------|
|`BigInt`|8|19|0|0|None|
|`Bit`|1|1|0|0|None|
|`DateTime`|8|23|3|0|None|
|`Decimal`|9|18|0|0|None|
|`Float`|8|53|0|0|None|
|`Image`|Max (-1)|0|0|0|None|
|`Int`|4|10|0|0|None|
|`Money`|8|19|4|0|None|
|`Ntext`|Max (-1)|0|0|\|IgnoreCase, IgnoreKanaType, IgnoreWidth|
|`Real`|4|24|0|0|None|
|`Row`|\|0|0|0|None|
|`SmallDateTime`|4|16|0|0|None|
|`SmallInt`|2|5|0|0|None|
|`SmallMoney`|4|10|4|0|None|
|`Text`|Max (-1)|0|0|\|IgnoreCase, IgnoreKanaType, IgnoreWidth|
|`TimeStamp`|8|0|0|0|None|
|`TinyInt`|1|3|0|0|None|
|`UniqueIdentifier`|16|0|0|0|None|
|`UDT`|\ or -1|0|0|0|None|
|`Variant`|8016|0|0|0|None|
|`Xml`|Max (-1)|0|0|0|IgnoreCase, IgnoreKanaType, IgnoreWidth|
]]>
The is .A that is not allowed was passed to the constructor as , or points to a type that does not have declared.
The name of the column.The SQL Server type of the parameter or column.The maximum length of the specified type.The precision of the parameter or column.The scale of the parameter or column.The locale ID of the parameter or column.The comparison rules of the parameter or column.A instance that points to the UDT.Specifies whether this column should use the default server value.Specifies if the column in the table-valued parameter is unique.Specifies the sort order for a column.Specifies the ordinal of the sort column.Initializes a new instance of the class with the specified column name, type, maximum length, precision, scale, locale ID, compare options, and user-defined type (UDT). This form of the constructor supports table-valued parameters by allowing you to specify if the column is unique in the table-valued parameter, the sort order for the column, and the ordinal of the sort column.
The name of the parameter or column.The SQL Server type of the parameter or column.The maximum length of the specified type.The locale ID of the parameter or column.The comparison rules of the parameter or column.Initializes a new instance of the class with the specified column name, type, maximum length, locale, and compare options.
, or -1, is allowed for a `dbType` of `Text` or `NText`.
For a `dbType` of `Varchar` or `Nvarchar`, a length specification of , or -1, declares the metadata as varchar(max) and nvarchar(max), respectively.
The following are the default values assigned to `dbType`, depending on the `SqlDbType` (the , , , and properties are set to `null`):
|SqlDbType|Precision|Scale|
|---------------|---------------|-----------|
|`Char`|0|0|
|`NChar`|0|0|
|`NText`|0|0|
|`NVarChar`|0|0|
|`Text`|0|0|
|`VarChar`|0|0|
]]>
The is .A SqlDbType that is not allowed was passed to the constructor as .
The name of the column.The SQL Server type of the parameter or column.The maximum length of the specified type.The locale ID of the parameter or column.The comparison rules of the parameter or column.Specifies whether this column should use the default server value.Specifies if the column in the table-valued parameter is unique.Specifies the sort order for a column.Specifies the ordinal of the sort column.Initializes a new instance of the class with the specified column name, type, maximum length, locale, compare options, and server default. This form of the constructor supports table-valued parameters by allowing you to specify if the column is unique in the table-valued parameter, the sort order for the column, and the ordinal of the sort column.
The name of the column.The SQL Server type of the parameter or column.The database name of the XML schema collection of a typed XML instance.The relational schema name of the XML schema collection of a typed XML instance.The name of the XML schema collection of a typed XML instance.Initializes a new instance of the class with the specified column name, type, database name, owning schema, and object name.
The is , or is when and are non-.A SqlDbType that is not allowed was passed to the constructor as .
The name of the column.The SQL Server type of the parameter or column.The database name of the XML schema collection of a typed XML instance.The relational schema name of the XML schema collection of a typed XML instance.The name of the XML schema collection of a typed XML instance.Specifies whether this column should use the default server value.Specifies if the column in the table-valued parameter is unique.Specifies the sort order for a column.Specifies the ordinal of the sort column.Initializes a new instance of the class with the specified column name, database name, owning schema, object name, and default server. This form of the constructor supports table-valued parameters by allowing you to specify if the column is unique in the table-valued parameter, the sort order for the column, and the ordinal of the sort column.
The name of the column.The SQL Server type of the parameter or column.A instance that points to the UDT.Initializes a new instance of the class with the specified column name, type, and user-defined type (UDT).
, , , and properties are set to `null`):
|SqlDbType|Maximum length|Precision|Scale|Locale|Compare options|
|---------------|--------------------|---------------|-----------|------------|---------------------|
|UDT|\ or -1|0|0|0|None|
]]>
The is .A SqlDbType that is not allowed was passed to the constructor as , or points to a type that does not have declared.
The name of the column.The SQL Server type of the parameter or column.A instance that points to the UDT.The SQL Server type name for .Initializes a new instance of the class with the specified column name, user-defined type (UDT), and SQLServer type.
The name of the column.The SQL Server type of the parameter or column.A instance that points to the UDT.The SQL Server type name for .Specifies whether this column should use the default server value.Specifies if the column in the table-valued parameter is unique.Specifies the sort order for a column.Specifies the ordinal of the sort column.Initializes a new instance of the class with the specified column name, type, user-defined type, SQL Server type, and server default. This form of the constructor supports table-valued parameters by allowing you to specify if the column is unique in the table-valued parameter, the sort order for the column, and the ordinal of the sort column.
Gets the comparison rules used for the column or parameter.The comparison rules used for the column or parameter as a .To be added.
Gets the data type of the column or parameter.The data type of the column or parameter as a .
.`String`.
]]>
Indicates if the column in the table-valued parameter is unique.A value.
constructors.
For more information, see [Table-Valued Parameters](/sql/connect/ado-net/sql/table-valued-parameters).
]]>
Gets the locale ID of the column or parameter.The locale ID of the column or parameter as a .
Gets the length of , , and data types.The length of , , and data types.
Gets the maximum length of the column or parameter.The maximum length of the column or parameter as a .
.`Row` this returns the number of columns in the row metadata instance.
The default value is 0.
]]>
Gets the name of the column or parameter.The name of the column or parameter as a .To be added.
Gets the precision of the column or parameter.The precision of the column or parameter as a .
Gets the scale of the column or parameter.The scale of the column or parameter.
Returns the sort order for a column.A object.
constructors.
For more information, see [Table-Valued Parameters](/sql/connect/ado-net/sql/table-valued-parameters).
]]>
Returns the ordinal of the sort column.The ordinal of the sort column.
constructors.
For more information, see [Table-Valued Parameters](/sql/connect/ado-net/sql/table-valued-parameters).
]]>
Gets the data type of the column or parameter.The data type of the column or parameter as a .
Gets the common language runtime (CLR) type of a user-defined type (UDT).The CLR type name of a user-defined type as a .
is not a UDT type. `Null` may also returned for valid UDT result sets where the assembly is not available to the application.
]]>
Gets the three-part name of the user-defined type (UDT) or the SQL Server type represented by the instance.The name of the UDT or SQL Server type as a .
Reports whether this column should use the default server value.A value.
constructors.
]]>
Gets the name of the database where the schema collection for this XML instance is located.The name of the database where the schema collection for this XML instance is located as a .
and are also null.
]]>
Gets the name of the schema collection for this XML instance.The name of the schema collection for this XML instance as a .
and are also `null`.
]]>
Gets the owning relational schema where the schema collection for this XML instance is located.The owning relational schema where the schema collection for this XML instance is located as a .
and are also `null`.
]]>
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified array of values against the metadata, and adjusts the value if necessary.The adjusted value as an array of values.To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified array of values against the metadata, and adjusts the value if necessary.The adjusted value as an array values.To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as an array of values.To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as a .To be added.
does not match the type, or could not be adjusted.
The value to validate against the instance.Validates the specified value against the metadata, and adjusts the value if necessary.The adjusted value as an array of values.To be added.
does not match the type, or could not be adjusted.
The object used from which the metadata is inferred.The name assigned to the returned instance.Infers the metadata from the specified object and returns it as a instance.The inferred metadata as a instance.To be added.The is .
Represents the Data Classification Sensitivity Information for columns as configured in Database.
Initializes a new instance of the class.List of sensitivity properties.
Returns the list of sensitivity properties as received from Server for this 'ColumnSensitivity' informationList of sensitivity properties.
Represents the Data Classification Information Types as received from SQL Server for the active 'SqlDataReader'
Initializes a new instance of the class.Name of Information Type.ID of Information Type.
Gets the ID for this 'InformationType' objectID of Information Type.
Gets the name for this 'InformationType' objectName of Information Type.
Represents the Data Classification Labels as received from SQL Server for the active 'SqlDataReader'
Initializes a new instance of the class.Name of label.ID of label.
Gets the ID for this 'Label' objectID of label.
Gets the name for this 'Label' objectName of label.
A relative ranking of the sensitivity of a query or of a column that is part of percolumn data.
It is an identifier based on a predefined set of values which define sensitivity rank. Used by other services like Advanced Threat Protection to detect anomalies based on their rank.
Provides the functionlity to retrieve Sensitivity Classification data as received from SQL Server for the active 'SqlDataReader'
Initializes a new instance of the class.List of labels.List of information types.List of column sensitivities.Relative sensitivity rank for the query associated with the active 'SqlDataReader'.
Returns the column sensitivity for this 'SensitivityClassification' ObjectList of column sensitivities.
Returns the information types collection for this 'SensitivityClassification' ObjectList of information types.
Returns the labels collection for this 'SensitivityClassification' ObjectList of labels.
Returns the relative sensitivity rank for the query associated with the active 'SqlDataReader'.Relative sensitivity ranking for this query.
Represents the Data Classification Sensitivity Information for columns as configured in Database.
Initializes a new instance of the class.Label for this SensitivityProperty.Information type for this SensitivityProperty.Sensitivity rank for this SensitivityProperty.
Returns the information type for this 'SensitivityProperty' ObjectInformation type for this SensitivityProperty.
Returns the label for this 'SensitivityProperty' ObjectLabel for this SensitivityProperty.
Returns the sensitivity rank for this 'SensitivityProperty' ObjectSensitivity rank for this SensitivityProperty.