SqlCommand Clase

Definición

Representa un procedimiento almacenado o una instrucción de Transact-SQL que se ejecuta en una base de datos de SQL Server.Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database. Esta clase no se puede heredar.This class cannot be inherited.

public ref class SqlCommand sealed : System::Data::Common::DbCommand, ICloneable, IDisposable
public sealed class SqlCommand : System.Data.Common.DbCommand, ICloneable, IDisposable
type SqlCommand = class
    inherit DbCommand
    interface IDbCommand
    interface ICloneable
    interface IDisposable
Public NotInheritable Class SqlCommand
Inherits DbCommand
Implements ICloneable, IDisposable
Herencia
Implementaciones

Ejemplos

En el ejemplo siguiente se crea un SqlConnection, un SqlCommandy un SqlDataReader.The following example creates a SqlConnection, a SqlCommand, and a SqlDataReader. En el ejemplo se leen los datos y se escriben en la consola.The example reads through the data, writing it to the console. Por último, en el ejemplo se cierra el SqlDataReader y, a continuación, el SqlConnection a medida que sale de los bloques de código Using.Finally, the example closes the SqlDataReader and then the SqlConnection as it exits the Using code blocks.

private static void ReadOrderData(string connectionString)
{
    string queryString = 
        "SELECT OrderID, CustomerID FROM dbo.Orders;";
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        using(SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                    reader[0], reader[1]));
            }
        }
    }
}
Public Sub ReadOrderData(ByVal connectionString As String)
    Dim queryString As String = _
        "SELECT OrderID, CustomerID FROM dbo.Orders;"
    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand(queryString, connection)
        connection.Open()
        Dim reader As SqlDataReader = command.ExecuteReader()
        Try
            While reader.Read()
                Console.WriteLine(String.Format("{0}, {1}", _
                    reader(0), reader(1)))
            End While
        Finally
            ' Always call Close when done reading.
            reader.Close()
        End Try
    End Using
End Sub

En el ejemplo siguiente se muestra cómo crear y ejecutar diferentes tipos de objetos SqlCommand.The following sample shows how to create and execute different types of SqlCommand objects.

En primer lugar, debe crear la base de datos de ejemplo ejecutando el siguiente script:First you must create the sample database, by executing the following script:

USE [master]  
GO  
  
CREATE DATABASE [MySchool]  
GO  
  
USE [MySchool]  
GO  
  
SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  
CREATE procedure [dbo].[CourseExtInfo] @CourseId int  
as  
select c.CourseID,c.Title,c.Credits,d.Name as DepartmentName  
from Course as c left outer join Department as d on c.DepartmentID=d.DepartmentID  
where c.CourseID=@CourseId  
  
GO  
  
SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  
create procedure [dbo].[DepartmentInfo] @DepartmentId int,@CourseCount int output  
as  
select @CourseCount=Count(c.CourseID)  
from course as c  
where c.DepartmentID=@DepartmentId  
  
select d.DepartmentID,d.Name,d.Budget,d.StartDate,d.Administrator  
from Department as d  
where d.DepartmentID=@DepartmentId  
  
GO  
  
SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  
Create PROCEDURE [dbo].[GetDepartmentsOfSpecifiedYear]   
@Year int,@BudgetSum money output  
AS  
BEGIN  
        SELECT @BudgetSum=SUM([Budget])  
  FROM [MySchool].[dbo].[Department]  
  Where YEAR([StartDate])=@Year   
  
SELECT [DepartmentID]  
      ,[Name]  
      ,[Budget]  
      ,[StartDate]  
      ,[Administrator]  
  FROM [MySchool].[dbo].[Department]  
  Where YEAR([StartDate])=@Year  
  
END  
GO  
  
SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  
CREATE TABLE [dbo].[Course]([CourseID] [nvarchar](10) NOT NULL,  
[Year] [smallint] NOT NULL,  
[Title] [nvarchar](100) NOT NULL,  
[Credits] [int] NOT NULL,  
[DepartmentID] [int] NOT NULL,  
 CONSTRAINT [PK_Course] PRIMARY KEY CLUSTERED   
(  
[CourseID] ASC,  
[Year] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]  
  
GO  
  
SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  
CREATE TABLE [dbo].[Department]([DepartmentID] [int] IDENTITY(1,1) NOT NULL,  
[Name] [nvarchar](50) NOT NULL,  
[Budget] [money] NOT NULL,  
[StartDate] [datetime] NOT NULL,  
[Administrator] [int] NULL,  
 CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED   
(  
[DepartmentID] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]  
  
GO  
  
SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  
CREATE TABLE [dbo].[Person]([PersonID] [int] IDENTITY(1,1) NOT NULL,  
[LastName] [nvarchar](50) NOT NULL,  
[FirstName] [nvarchar](50) NOT NULL,  
[HireDate] [datetime] NULL,  
[EnrollmentDate] [datetime] NULL,  
 CONSTRAINT [PK_School.Student] PRIMARY KEY CLUSTERED   
(  
[PersonID] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]  
  
GO  
  
SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  
CREATE TABLE [dbo].[StudentGrade]([EnrollmentID] [int] IDENTITY(1,1) NOT NULL,  
[CourseID] [nvarchar](10) NOT NULL,  
[StudentID] [int] NOT NULL,  
[Grade] [decimal](3, 2) NOT NULL,  
 CONSTRAINT [PK_StudentGrade] PRIMARY KEY CLUSTERED   
(  
[EnrollmentID] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]  
  
GO  
  
SET ANSI_NULLS ON  
GO  
SET QUOTED_IDENTIFIER ON  
GO  
create view [dbo].[EnglishCourse]  
as  
select c.CourseID,c.Title,c.Credits,c.DepartmentID  
from Course as c join Department as d on c.DepartmentID=d.DepartmentID  
where d.Name=N'English'  
  
GO  
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C1045', 2012, N'Calculus', 4, 7)  
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C1061', 2012, N'Physics', 4, 1)  
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C2021', 2012, N'Composition', 3, 2)  
INSERT [dbo].[Course] ([CourseID], [Year], [Title], [Credits], [DepartmentID]) VALUES (N'C2042', 2012, N'Literature', 4, 2)  
SET IDENTITY_INSERT [dbo].[Department] ON   
  
INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (1, N'Engineering', 350000.0000, CAST(0x0000999C00000000 AS DateTime), 2)  
INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (2, N'English', 120000.0000, CAST(0x0000999C00000000 AS DateTime), 6)  
INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (4, N'Economics', 200000.0000, CAST(0x0000999C00000000 AS DateTime), 4)  
INSERT [dbo].[Department] ([DepartmentID], [Name], [Budget], [StartDate], [Administrator]) VALUES (7, N'Mathematics', 250024.0000, CAST(0x0000999C00000000 AS DateTime), 3)  
SET IDENTITY_INSERT [dbo].[Department] OFF  
SET IDENTITY_INSERT [dbo].[Person] ON   
  
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (1, N'Hu', N'Nan', NULL, CAST(0x0000A0BF00000000 AS DateTime))  
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (2, N'Norman', N'Laura', NULL, CAST(0x0000A0BF00000000 AS DateTime))  
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (3, N'Olivotto', N'Nino', NULL, CAST(0x0000A0BF00000000 AS DateTime))  
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (4, N'Anand', N'Arturo', NULL, CAST(0x0000A0BF00000000 AS DateTime))  
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (5, N'Jai', N'Damien', NULL, CAST(0x0000A0BF00000000 AS DateTime))  
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (6, N'Holt', N'Roger', CAST(0x000097F100000000 AS DateTime), NULL)  
INSERT [dbo].[Person] ([PersonID], [LastName], [FirstName], [HireDate], [EnrollmentDate]) VALUES (7, N'Martin', N'Randall', CAST(0x00008B1A00000000 AS DateTime), NULL)  
SET IDENTITY_INSERT [dbo].[Person] OFF  
SET IDENTITY_INSERT [dbo].[StudentGrade] ON   
  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (1, N'C1045', 1, CAST(3.50 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (2, N'C1045', 2, CAST(3.00 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (3, N'C1045', 3, CAST(2.50 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (4, N'C1045', 4, CAST(4.00 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (5, N'C1045', 5, CAST(3.50 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (6, N'C1061', 1, CAST(4.00 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (7, N'C1061', 3, CAST(3.50 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (8, N'C1061', 4, CAST(2.50 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (9, N'C1061', 5, CAST(1.50 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (10, N'C2021', 1, CAST(2.50 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (11, N'C2021', 2, CAST(3.50 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (12, N'C2021', 4, CAST(3.00 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (13, N'C2021', 5, CAST(3.00 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (14, N'C2042', 1, CAST(2.00 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (15, N'C2042', 2, CAST(3.50 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (16, N'C2042', 3, CAST(4.00 AS Decimal(3, 2)))  
INSERT [dbo].[StudentGrade] ([EnrollmentID], [CourseID], [StudentID], [Grade]) VALUES (17, N'C2042', 5, CAST(3.00 AS Decimal(3, 2)))  
SET IDENTITY_INSERT [dbo].[StudentGrade] OFF  
ALTER TABLE [dbo].[Course]  WITH CHECK ADD  CONSTRAINT [FK_Course_Department] FOREIGN KEY([DepartmentID])  
REFERENCES [dbo].[Department] ([DepartmentID])  
GO  
ALTER TABLE [dbo].[Course] CHECK CONSTRAINT [FK_Course_Department]  
GO  
ALTER TABLE [dbo].[StudentGrade]  WITH CHECK ADD  CONSTRAINT [FK_StudentGrade_Student] FOREIGN KEY([StudentID])  
REFERENCES [dbo].[Person] ([PersonID])  
GO  
ALTER TABLE [dbo].[StudentGrade] CHECK CONSTRAINT [FK_StudentGrade_Student]  
GO  

A continuación, compile y ejecute lo siguiente:Next, compile and execute the following:

using System;  
using System.Data;  
using System.Data.SqlClient;  
using System.Threading.Tasks;  
  
class Program {  
  
   static class SqlHelper {  
      // Set the connection, command, and then execute the command with non query.  
      public static Int32 ExecuteNonQuery(String connectionString, String commandText,  
          CommandType commandType, params SqlParameter[] parameters) {  
         using (SqlConnection conn = new SqlConnection(connectionString)) {  
            using (SqlCommand cmd = new SqlCommand(commandText, conn)) {  
               // There're three command types: StoredProcedure, Text, TableDirect. The TableDirect   
               // type is only for OLE DB.    
               cmd.CommandType = commandType;  
               cmd.Parameters.AddRange(parameters);  
  
               conn.Open();  
               return cmd.ExecuteNonQuery();  
            }  
         }  
      }  
  
      // Set the connection, command, and then execute the command and only return one value.  
      public static Object ExecuteScalar(String connectionString, String commandText,  
          CommandType commandType, params SqlParameter[] parameters) {  
         using (SqlConnection conn = new SqlConnection(connectionString)) {  
            using (SqlCommand cmd = new SqlCommand(commandText, conn)) {  
               cmd.CommandType = commandType;  
               cmd.Parameters.AddRange(parameters);  
  
               conn.Open();  
               return cmd.ExecuteScalar();  
            }  
         }  
      }  
  
      // Set the connection, command, and then execute the command with query and return the reader.  
      public static SqlDataReader ExecuteReader(String connectionString, String commandText,  
          CommandType commandType, params SqlParameter[] parameters) {  
         SqlConnection conn = new SqlConnection(connectionString);  
  
         using (SqlCommand cmd = new SqlCommand(commandText, conn)) {  
            cmd.CommandType = commandType;  
            cmd.Parameters.AddRange(parameters);  
  
            conn.Open();  
            // When using CommandBehavior.CloseConnection, the connection will be closed when the   
            // IDataReader is closed.  
            SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);  
  
            return reader;  
         }  
      }  
   }  
  
   static void Main(string[] args) {  
      String connectionString = "Data Source=(local);Initial Catalog=MySchool;Integrated Security=True;Asynchronous Processing=true;";  
  
      CountCourses(connectionString, 2012);  
      Console.WriteLine();  
  
      Console.WriteLine("Following result is the departments that started from 2007:");  
      GetDepartments(connectionString, 2007);  
      Console.WriteLine();  
  
      Console.WriteLine("Add the credits when the credits of course is lower than 4.");  
      AddCredits(connectionString, 4);  
      Console.WriteLine();  
  
      Console.WriteLine("Please press any key to exit...");  
      Console.ReadKey();  
   }  
  
   static void CountCourses(String connectionString, Int32 year) {  
      String commandText = "Select Count([CourseID]) FROM [MySchool].[dbo].[Course] Where Year=@Year";  
      SqlParameter parameterYear = new SqlParameter("@Year", SqlDbType.Int);  
      parameterYear.Value = year;  
  
      Object oValue = SqlHelper.ExecuteScalar(connectionString, commandText, CommandType.Text, parameterYear);  
      Int32 count;  
      if (Int32.TryParse(oValue.ToString(), out count))  
         Console.WriteLine("There {0} {1} course{2} in {3}.", count > 1 ? "are" : "is", count, count > 1 ? "s" : null, year);  
   }  
  
   // Display the Departments that start from the specified year.  
   static void GetDepartments(String connectionString, Int32 year) {  
      String commandText = "dbo.GetDepartmentsOfSpecifiedYear";  
  
      // Specify the year of StartDate  
      SqlParameter parameterYear = new SqlParameter("@Year", SqlDbType.Int);  
      parameterYear.Value = year;  
  
      // When the direction of parameter is set as Output, you can get the value after   
      // executing the command.  
      SqlParameter parameterBudget = new SqlParameter("@BudgetSum", SqlDbType.Money);  
      parameterBudget.Direction = ParameterDirection.Output;  
  
      using (SqlDataReader reader = SqlHelper.ExecuteReader(connectionString, commandText,  
          CommandType.StoredProcedure, parameterYear, parameterBudget)) {  
         Console.WriteLine("{0,-20}{1,-20}{2,-20}{3,-20}", "Name", "Budget", "StartDate",  
             "Administrator");  
         while (reader.Read()) {  
            Console.WriteLine("{0,-20}{1,-20:C}{2,-20:d}{3,-20}", reader["Name"],  
                reader["Budget"], reader["StartDate"], reader["Administrator"]);  
         }  
      }  
      Console.WriteLine("{0,-20}{1,-20:C}", "Sum:", parameterBudget.Value);  
   }  
  
   // If credits of course is lower than the certain value, the method will add the credits.  
   static void AddCredits(String connectionString, Int32 creditsLow) {  
      String commandText = "Update [MySchool].[dbo].[Course] Set Credits=Credits+1 Where Credits<@Credits";  
  
      SqlParameter parameterCredits = new SqlParameter("@Credits", creditsLow);  
  
      Int32 rows = SqlHelper.ExecuteNonQuery(connectionString, commandText, CommandType.Text, parameterCredits);  
  
      Console.WriteLine("{0} row{1} {2} updated.", rows, rows > 1 ? "s" : null, rows > 1 ? "are" : "is");  
   }  
}  

Comentarios

Cuando se crea una instancia de SqlCommand, las propiedades de lectura y escritura se establecen en sus valores iniciales.When an instance of SqlCommand is created, the read/write properties are set to their initial values. Para obtener una lista de estos valores, vea el constructor SqlCommand.For a list of these values, see the SqlCommand constructor.

SqlCommand incluye los siguientes métodos para ejecutar comandos en una base de datos SQL Server:SqlCommand features the following methods for executing commands at a SQL Server database:

ElementoItem DescripciónDescription
BeginExecuteNonQuery Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe este SqlCommand, que normalmente ejecuta comandos como INSERT, DELETE, UPDATE y SET.Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, generally executing commands such as INSERT, DELETE, UPDATE, and SET statements. Cada llamada a BeginExecuteNonQuery se debe emparejar con una llamada a EndExecuteNonQuery que finaliza la operación, normalmente en un subproceso independiente.Each call to BeginExecuteNonQuery must be paired with a call to EndExecuteNonQuery which finishes the operation, typically on a separate thread.
BeginExecuteReader Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe este SqlCommand y recupera uno o más conjuntos de resultados del servidor.Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and retrieves one or more results sets from the server. Cada llamada a BeginExecuteReader se debe emparejar con una llamada a EndExecuteReader que finaliza la operación, normalmente en un subproceso independiente.Each call to BeginExecuteReader must be paired with a call to EndExecuteReader which finishes the operation, typically on a separate thread.
BeginExecuteXmlReader Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe SqlCommand.Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand. Cada llamada a BeginExecuteXmlReader se debe emparejar con una llamada a EndExecuteXmlReader, que finaliza la operación, normalmente en un subproceso independiente, y devuelve un objeto XmlReader.Each call to BeginExecuteXmlReader must be paired with a call to EndExecuteXmlReader, which finishes the operation, typically on a separate thread, and returns an XmlReader object.
ExecuteReader Ejecuta comandos que devuelven filas.Executes commands that return rows. Para mejorar el rendimiento, ExecuteReader invoca comandos mediante el procedimiento almacenado del sistema sp_executesql de Transact-SQL.For increased performance, ExecuteReader invokes commands using the Transact-SQL sp_executesql system stored procedure. Por lo tanto, es posible que ExecuteReader no tenga el efecto deseado si se usa para ejecutar comandos como instrucciones SET de Transact-SQL.Therefore, ExecuteReader might not have the effect that you want if used to execute commands such as Transact-SQL SET statements.
ExecuteNonQuery Ejecuta comandos como las instrucciones INSERT, DELETE, UPDATE y SET de Transact-SQL.Executes commands such as Transact-SQL INSERT, DELETE, UPDATE, and SET statements.
ExecuteScalar Recupera un valor único (por ejemplo, un valor agregado) de una base de datos.Retrieves a single value (for example, an aggregate value) from a database.
ExecuteXmlReader Envía CommandText a Connection y crea un objeto XmlReader.Sends the CommandText to the Connection and builds an XmlReader object.

Puede restablecer la propiedad CommandText y volver a usar el objeto SqlCommand.You can reset the CommandText property and reuse the SqlCommand object. Sin embargo, debe cerrar el SqlDataReader antes de poder ejecutar un comando nuevo o anterior.However, you must close the SqlDataReader before you can execute a new or previous command.

Si un SqlException se genera mediante el método que ejecuta una SqlCommand, el SqlConnection permanece abierto cuando el nivel de gravedad es 19 o menos.If a SqlException is generated by the method executing a SqlCommand, the SqlConnection remains open when the severity level is 19 or less. Cuando el nivel de gravedad es 20 o superior, el servidor cierra normalmente el SqlConnection.When the severity level is 20 or greater, the server ordinarily closes the SqlConnection. Sin embargo, el usuario puede volver a abrir la conexión y continuar.However, the user can reopen the connection and continue.

Nota

El proveedor de datos de .NET Framework para SQL Server no admite los parámetros con nombre, también denominados ordinales.Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server.

Constructores

SqlCommand()

Inicializa una nueva instancia de la clase SqlCommand.Initializes a new instance of the SqlCommand class.

SqlCommand(String)

Inicializa una nueva instancia de la clase SqlCommand con el texto de la consulta.Initializes a new instance of the SqlCommand class with the text of the query.

SqlCommand(String, SqlConnection)

Inicializa una nueva instancia de la clase SqlCommand con el texto de la consulta y una conexión SqlConnection.Initializes a new instance of the SqlCommand class with the text of the query and a SqlConnection.

SqlCommand(String, SqlConnection, SqlTransaction)

Inicializa una nueva instancia de la clase SqlCommand con el texto de la consulta, un objeto SqlConnection y el objeto SqlTransaction.Initializes a new instance of the SqlCommand class with the text of the query, a SqlConnection, and the SqlTransaction.

SqlCommand(String, SqlConnection, SqlTransaction, SqlCommandColumnEncryptionSetting)

Inicializa una nueva instancia de la clase SqlCommand con texto de comando especificado, conexión, transacción y configuración de cifrado.Initializes a new instance of the SqlCommand class with specified command text, connection, transaction, and encryption setting.

Propiedades

CanRaiseEvents

Obtiene un valor que indica si el componente puede generar un evento.Gets a value indicating whether the component can raise an event.

(Heredado de Component)
ColumnEncryptionSetting

Obtiene o establece la configuración del cifrado de columnas para este comando.Gets or sets the column encryption setting for this command.

CommandText

Obtiene o establece la instrucción de Transact-SQL, el nombre de tabla o el procedimiento almacenado que se ejecutan en el origen de datos.Gets or sets the Transact-SQL statement, table name or stored procedure to execute at the data source.

CommandTimeout

Obtiene o establece el tiempo de espera (en segundos) hasta que se interrumpe el intento de ejecutar un comando y se genera un error.Gets or sets the wait time (in seconds) before terminating the attempt to execute a command and generating an error.

CommandType

Obtiene o establece un valor que indica cómo se interpreta la propiedad CommandText.Gets or sets a value indicating how the CommandText property is to be interpreted.

Connection

Obtiene o establece la interfaz SqlConnection que usa esta instancia de SqlCommand.Gets or sets the SqlConnection used by this instance of the SqlCommand.

Container

Obtiene IContainer que contiene Component.Gets the IContainer that contains the Component.

(Heredado de Component)
DbConnection

Cuando se invalida en una clase derivada, obtiene o establece la instancia de DbConnection que usa este elemento DbCommand.When overridden in a derived class, gets or sets the DbConnection used by this DbCommand.

(Heredado de DbCommand)
DbParameterCollection

Cuando se invalida en una clase derivada, obtiene la colección de objetos DbParameter.When overridden in a derived class, gets the collection of DbParameter objects.

(Heredado de DbCommand)
DbTransaction

Cuando se invalida en una clase derivada, obtiene o establece el elemento DbTransaction en el que se ejecuta este objeto DbCommand.When overridden in a derived class, gets or sets the DbTransaction within which this DbCommand object executes.

(Heredado de DbCommand)
DesignMode

Obtiene un valor que indica si Component está actualmente en modo de diseño.Gets a value that indicates whether the Component is currently in design mode.

(Heredado de Component)
DesignTimeVisible

Obtiene o establece un valor que indica si el objeto de comando debe estar visible en un control del Diseñador de Windows Forms.Gets or sets a value indicating whether the command object should be visible in a Windows Form Designer control.

Events

Obtiene la lista de controladores de eventos asociados a Component.Gets the list of event handlers that are attached to this Component.

(Heredado de Component)
Notification

Obtiene o establece un valor que especifica el objeto SqlNotificationRequest enlazado a este comando.Gets or sets a value that specifies the SqlNotificationRequest object bound to this command.

NotificationAutoEnlist

Obtiene o establece un valor que indica si la aplicación debe recibir automáticamente notificaciones de consulta de un objeto SqlDependency común.Gets or sets a value indicating whether the application should automatically receive query notifications from a common SqlDependency object.

Parameters

Obtiene la SqlParameterCollection.Gets the SqlParameterCollection.

Site

Obtiene o establece el ISite de Component.Gets or sets the ISite of the Component.

(Heredado de Component)
Transaction

Obtiene o establece la transacción SqlTransaction en la que se ejecuta SqlCommand.Gets or sets the SqlTransaction within which the SqlCommand executes.

UpdatedRowSource

Obtiene o establece la manera en que se aplican los resultados del comando a DataRow cuando lo utiliza el método Update de DbDataAdapter.Gets or sets how command results are applied to the DataRow when used by the Update method of the DbDataAdapter.

Métodos

BeginExecuteNonQuery()

Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe SqlCommand.Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand.

BeginExecuteNonQuery(AsyncCallback, Object)

Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe SqlCommand, dados un procedimiento de devolución de llamada e información de estado.Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, given a callback procedure and state information.

BeginExecuteReader()

Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe SqlCommandy recupera uno o varios conjuntos de resultados del servidor.Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, and retrieves one or more result sets from the server.

BeginExecuteReader(AsyncCallback, Object)

Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe SqlCommand y recupera uno o varios conjuntos de resultados del servidor, dados un procedimiento de devolución de llamada e información de estado.Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and retrieves one or more result sets from the server, given a callback procedure and state information.

BeginExecuteReader(AsyncCallback, Object, CommandBehavior)

Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe SqlCommand, utilizando uno de los valores de CommandBehavior y recuperando uno o varios conjuntos de resultados del servidor, a partir del procedimiento de devolución de llamada e información de estado dados.Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand, using one of the CommandBehavior values, and retrieving one or more result sets from the server, given a callback procedure and state information.

BeginExecuteReader(CommandBehavior)

Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe SqlCommand utilizando uno de los valores de CommandBehavior .Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand using one of the CommandBehavior values.

BeginExecuteXmlReader()

Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe SqlCommand y devuelve los resultados como un objeto XmlReader .Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and returns results as an XmlReader object.

BeginExecuteXmlReader(AsyncCallback, Object)

Inicia la ejecución asincrónica de la instrucción de Transact-SQL o del procedimiento almacenado que describe SqlCommand y devuelve los resultados como un objeto XmlReader a través de un procedimiento de devolución de llamada.Initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this SqlCommand and returns results as an XmlReader object, using a callback procedure.

Cancel()

Intenta cancelar la ejecución de un SqlCommand.Tries to cancel the execution of a SqlCommand.

Clone()

Crea un nuevo objeto SqlCommand que es una copia de la instancia actual.Creates a new SqlCommand object that is a copy of the current instance.

CreateDbParameter()

Cuando se invalida en una clase derivada, crea una instancia de un objeto DbParameter.When overridden in a derived class, creates a new instance of a DbParameter object.

(Heredado de DbCommand)
CreateObjRef(Type)

Crea un objeto que contiene toda la información relevante necesaria para generar un proxy utilizado para comunicarse con un objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Heredado de MarshalByRefObject)
CreateParameter()

Crea una nueva instancia de un objeto SqlParameter.Creates a new instance of a SqlParameter object.

Dispose()

Libera todos los recursos que ha usado el objeto Component.Releases all resources used by the Component.

(Heredado de Component)
Dispose(Boolean)

Libera los recursos no administrados que usa el objeto Component y, opcionalmente, libera los recursos administrados.Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Heredado de Component)
DisposeAsync()

Desecha de forma asincrónica el objeto de comando.Asynchronously diposes the command object.

(Heredado de DbCommand)
EndExecuteNonQuery(IAsyncResult)

Finaliza la ejecución asincrónica de una instrucción de Transact-SQL.Finishes asynchronous execution of a Transact-SQL statement.

EndExecuteReader(IAsyncResult)

Finaliza la ejecución asincrónica de una instrucción de Transact-SQL y devuelve el objeto SqlDataReadersolicitado.Finishes asynchronous execution of a Transact-SQL statement, returning the requested SqlDataReader.

EndExecuteXmlReader(IAsyncResult)

Finaliza la ejecución asincrónica de una instrucción de Transact-SQL y devuelve los datos solicitados como XML.Finishes asynchronous execution of a Transact-SQL statement, returning the requested data as XML.

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Heredado de Object)
ExecuteDbDataReader(CommandBehavior)

Cuando se invalida en una clase derivada, ejecuta el texto de comando en la conexión.When overridden in a derived class, executes the command text against the connection.

(Heredado de DbCommand)
ExecuteDbDataReaderAsync(CommandBehavior, CancellationToken)

Los proveedores deben implementar este método para proporcionar una implementación no predeterminada para las sobrecargas de ExecuteReader.Providers should implement this method to provide a non-default implementation for ExecuteReader overloads.

La implementación predeterminada invoca el método sincrónico ExecuteReader() y devuelve una tarea completada, bloqueando el subproceso de llamada.The default implementation invokes the synchronous ExecuteReader() method and returns a completed task, blocking the calling thread. La implementación predeterminada devolverá una tarea cancelada si se pasa un token de cancelación ya cancelado.The default implementation will return a cancelled task if passed an already cancelled cancellation token. Las excepciones producidas por ExecuteReader se comunicarán mediante la propiedad Task Exception devuelta.Exceptions thrown by ExecuteReader will be communicated via the returned Task Exception property.

Este método acepta un token de cancelación que se puede usar para solicitar que la operación se cancele pronto.This method accepts a cancellation token that can be used to request the operation to be cancelled early. Las implementaciones pueden omitir esta solicitud.Implementations may ignore this request.

(Heredado de DbCommand)
ExecuteNonQuery()

Ejecuta una instrucción de Transact-SQL en la conexión y devuelve el número de filas afectadas.Executes a Transact-SQL statement against the connection and returns the number of rows affected.

ExecuteNonQueryAsync()

Una versión asincrónica de ExecuteNonQuery(), que ejecuta una instrucción SQL con un objeto de conexión.An asynchronous version of ExecuteNonQuery(), which executes a SQL statement against a connection object.

Invoca ExecuteNonQueryAsync(CancellationToken) con CancellationToken.None.Invokes ExecuteNonQueryAsync(CancellationToken) with CancellationToken.None.

(Heredado de DbCommand)
ExecuteNonQueryAsync(CancellationToken)

Versión asincrónica de ExecuteNonQuery(), que ejecuta una instrucción de Transact-SQLTransact-SQL con la conexión y devuelve el número de filas afectadas.An asynchronous version of ExecuteNonQuery(), which executes a Transact-SQLTransact-SQL statement against the connection and returns the number of rows affected. Token de cancelación que se puede usar para solicitar que se abandone la operación antes de que transcurra el tiempo de espera del comando.The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Las excepciones se mostrarán a través del objeto Task devuelto.Exceptions will be reported via the returned Task object.

ExecuteReader()

Envía la propiedad CommandText a Connection y crea un objeto SqlDataReader.Sends the CommandText to the Connection and builds a SqlDataReader.

ExecuteReader(CommandBehavior)

Envía CommandText a Connectiony crea un SqlDataReader mediante uno de los valores de CommandBehavior .Sends the CommandText to the Connection, and builds a SqlDataReader using one of the CommandBehavior values.

ExecuteReaderAsync()

Una versión asincrónica de ExecuteReader(), que envía la propiedad CommandText a la propiedad Connection y compila SqlDataReader.An asynchronous version of ExecuteReader(), which sends the CommandText to the Connection and builds a SqlDataReader. Las excepciones se mostrarán a través del objeto Task devuelto.Exceptions will be reported via the returned Task object.

ExecuteReaderAsync(CancellationToken)

Una versión asincrónica de ExecuteReader(), que envía la propiedad CommandText a la propiedad Connection y compila SqlDataReader.An asynchronous version of ExecuteReader(), which sends the CommandText to the Connection and builds a SqlDataReader.

Token de cancelación que se puede usar para solicitar que se abandone la operación antes de que transcurra el tiempo de espera del comando.The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Las excepciones se mostrarán a través del objeto Task devuelto.Exceptions will be reported via the returned Task object.

ExecuteReaderAsync(CommandBehavior)

Versión asincrónica de ExecuteReader(CommandBehavior), que envía la propiedad CommandText a la propiedad Connectiony compila SqlDataReader.An asynchronous version of ExecuteReader(CommandBehavior), which sends the CommandText to the Connection, and builds a SqlDataReader. Las excepciones se mostrarán a través del objeto Task devuelto.Exceptions will be reported via the returned Task object.

ExecuteReaderAsync(CommandBehavior, CancellationToken)

Versión asincrónica de ExecuteReader(CommandBehavior), que envía la propiedad CommandText a la propiedad Connectiony compila SqlDataReaderAn asynchronous version of ExecuteReader(CommandBehavior), which sends the CommandText to the Connection, and builds a SqlDataReader

Token de cancelación que se puede usar para solicitar que se abandone la operación antes de que transcurra el tiempo de espera del comando.The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Las excepciones se mostrarán a través del objeto Task devuelto.Exceptions will be reported via the returned Task object.

ExecuteScalar()

Ejecuta la consulta y devuelve la primera columna de la primera fila del conjunto de resultados devueltos por la consulta.Executes the query, and returns the first column of the first row in the result set returned by the query. Las demás columnas o filas no se tienen en cuenta.Additional columns or rows are ignored.

ExecuteScalarAsync()

Una versión asincrónica de ExecuteScalar() que ejecuta la consulta y devuelve la primera columna de la primera fila del conjunto de resultados que devuelve la consulta.An asynchronous version of ExecuteScalar(), which executes the query and returns the first column of the first row in the result set returned by the query. Se omiten todas las demás columnas y filas.All other columns and rows are ignored.

Invoca ExecuteScalarAsync(CancellationToken) con CancellationToken.None.Invokes ExecuteScalarAsync(CancellationToken) with CancellationToken.None.

(Heredado de DbCommand)
ExecuteScalarAsync(CancellationToken)

Versión asincrónica de ExecuteScalar()que ejecuta la consulta asincrónicamente y devuelve la primera columna de la primera fila del conjunto de resultados que devuelve la consulta.An asynchronous version of ExecuteScalar(), which executes the query asynchronously and returns the first column of the first row in the result set returned by the query. Las demás columnas o filas no se tienen en cuenta.Additional columns or rows are ignored.

Token de cancelación que se puede usar para solicitar que se abandone la operación antes de que transcurra el tiempo de espera del comando.The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Las excepciones se mostrarán a través del objeto Task devuelto.Exceptions will be reported via the returned Task object.

ExecuteXmlReader()

Envía CommandText a Connection y crea un objeto XmlReader.Sends the CommandText to the Connection and builds an XmlReader object.

ExecuteXmlReaderAsync()

Una versión asincrónica de ExecuteXmlReader(), que envía la propiedad CommandText a la propiedad Connection y compila un objeto XmlReader .An asynchronous version of ExecuteXmlReader(), which sends the CommandText to the Connection and builds an XmlReader object.

Las excepciones se mostrarán a través del objeto Task devuelto.Exceptions will be reported via the returned Task object.

ExecuteXmlReaderAsync(CancellationToken)

Una versión asincrónica de ExecuteXmlReader(), que envía la propiedad CommandText a la propiedad Connection y compila un objeto XmlReader .An asynchronous version of ExecuteXmlReader(), which sends the CommandText to the Connection and builds an XmlReader object.

Token de cancelación que se puede usar para solicitar que se abandone la operación antes de que transcurra el tiempo de espera del comando.The cancellation token can be used to request that the operation be abandoned before the command timeout elapses. Las excepciones se mostrarán a través del objeto Task devuelto.Exceptions will be reported via the returned Task object.

GetHashCode()

Sirve como función hash predeterminada.Serves as the default hash function.

(Heredado de Object)
GetLifetimeService()

Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Heredado de MarshalByRefObject)
GetService(Type)

Devuelve un objeto que representa el servicio suministrado por Component o por Container.Returns an object that represents a service provided by the Component or by its Container.

(Heredado de Component)
GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Heredado de Object)
InitializeLifetimeService()

Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia.Obtains a lifetime service object to control the lifetime policy for this instance.

(Heredado de MarshalByRefObject)
MemberwiseClone()

Crea una copia superficial del Object actual.Creates a shallow copy of the current Object.

(Heredado de Object)
MemberwiseClone(Boolean)

Crea una copia superficial del objeto MarshalByRefObject actual.Creates a shallow copy of the current MarshalByRefObject object.

(Heredado de MarshalByRefObject)
Prepare()

Crea una versión preparada del comando en una instancia de SQL Server.Creates a prepared version of the command on an instance of SQL Server.

PrepareAsync(CancellationToken)

Crea de forma asincrónica una versión preparada (o compilada) del comando en el origen de datos.Asynchronously creates a prepared (or compiled) version of the command on the data source.

(Heredado de DbCommand)
ResetCommandTimeout()

Restablece el valor predeterminado de la propiedad CommandTimeout.Resets the CommandTimeout property to its default value.

ToString()

Devuelve una String que contiene el nombre del Component, si existe.Returns a String containing the name of the Component, if any. Este método no se debe invalidar.This method should not be overridden.

(Heredado de Component)

Eventos

Disposed

Se produce cuando el componente se elimina mediante una llamada al método Dispose().Occurs when the component is disposed by a call to the Dispose() method.

(Heredado de Component)
StatementCompleted

Se produce cuando finaliza la ejecución de una instrucción Transact-SQL.Occurs when the execution of a Transact-SQL statement completes.

Implementaciones de interfaz explícitas

ICloneable.Clone()

Crea un nuevo objeto SqlCommand que es una copia de la instancia actual.Creates a new SqlCommand object that is a copy of the current instance.

IDbCommand.Connection

Obtiene o establece la interfaz IDbConnection que usa esta instancia de IDbCommand.Gets or sets the IDbConnection used by this instance of the IDbCommand.

(Heredado de DbCommand)
IDbCommand.CreateParameter()

Crea una nueva instancia de un objeto SqlParameter.Creates a new instance of a SqlParameter object.

IDbCommand.ExecuteReader()

Envía la propiedad CommandText a la propiedad Connection y compila un objeto SqlDataReader.Sends the CommandText to the Connection, and builds a SqlDataReader.

IDbCommand.ExecuteReader(CommandBehavior)

Envía CommandText a Connectiony crea un SqlDataReader mediante uno de los valores de CommandBehavior .Sends the CommandText to the Connection, and builds a SqlDataReader using one of the CommandBehavior values.

IDbCommand.Parameters

Obtiene la IDataParameterCollection.Gets the IDataParameterCollection.

(Heredado de DbCommand)
IDbCommand.Transaction

Obtiene o establece DbTransaction dentro del cual se ejecuta este objeto DbCommand.Gets or sets the DbTransaction within which this DbCommand object executes.

(Heredado de DbCommand)

Se aplica a

Consulte también: