System.Data.SqlClient.SqlCommand

Overview

The SqlCommand class represents a Transact-SQL statement or stored procedure to execute against a SQL Server database. It provides functionality for executing commands, retrieving results, and managing parameters.

Syntax

public sealed class SqlCommand : DbCommand, ICloneable, IDbCommand, IDbDataParameter, IDataParameter, IDisposable, ICloneable, IAsyncResult

Constructors

SignatureDescription
SqlCommand()Initializes a new instance of the SqlCommand class.
SqlCommand(string cmdText)Initializes with the specified command text.
SqlCommand(string cmdText, SqlConnection connection)Initializes with command text and a connection.
SqlCommand(string cmdText, SqlConnection connection, SqlTransaction transaction)Initializes with command text, connection, and transaction.

Properties

NameTypeDescription
CommandTextstringThe Transact-SQL statement or stored procedure to execute.
CommandTypeCommandTypeSpecifies how the CommandText property is interpreted.
ConnectionSqlConnectionThe database connection used by the command.
ParametersSqlParameterCollectionCollection of parameters for the command.
TransactionSqlTransactionThe transaction within which the command executes.
TimeoutintTime (seconds) to wait for command execution.

Methods

Execute methods

MethodReturn TypeDescription
ExecuteNonQuery()intExecutes a command that does not return rows.
ExecuteReader()SqlDataReaderExecutes the command and returns a data reader.
ExecuteScalar()objectExecutes the command and returns the first column of the first row.

Asynchronous methods

MethodReturn TypeDescription
ExecuteNonQueryAsync(CancellationToken)Task<int>Asynchronously executes a command that does not return rows.
ExecuteReaderAsync(CancellationToken)Task<SqlDataReader>Asynchronously executes the command and returns a data reader.
ExecuteScalarAsync(CancellationToken)Task<object>Asynchronously executes the command and returns the first column of the first row.

Miscellaneous methods

MethodReturn TypeDescription
Cancel()voidCancels the execution of the command.
CreateParameter()SqlParameterCreates a new parameter object.
Prepare()voidPrepares the command on the data source.

Examples

Executing a query and reading results

using (SqlConnection conn = new SqlConnection(connectionString))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM Products", conn))
    {
        using (SqlDataReader reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                int id = reader.GetInt32(0);
                string name = reader.GetString(1);
                Console.WriteLine($"{id}: {name}");
            }
        }
    }
}

Using parameters with a stored procedure

using (SqlConnection conn = new SqlConnection(connectionString))
{
    conn.Open();
    using (SqlCommand cmd = new SqlCommand("dbo.GetProductById", conn))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@ProductId", SqlDbType.Int) { Value = 42 });
        var result = cmd.ExecuteScalar();
        Console.WriteLine($"Product Name: {result}");
    }
}