명령 실행

적용 대상: .NET Framework .NET .NET Standard

ADO.NET 다운로드

Microsoft SqlClient Data Provider for SQL Server에는 DbCommand에서 상속되는 SqlCommand 개체가 있습니다. 이 개체는 명령의 유형 및 원하는 반환 값을 기준으로 명령 실행을 위한 메서드를 노출합니다. 다음 표에는 이러한 명령 및 해당 반환 값이 나와 있습니다.

명령 Return Value
ExecuteReader DataReader 개체를 반환합니다.
ExecuteScalar 단일 스칼라 값을 반환합니다.
ExecuteNonQuery 어떠한 행도 반환하지 않는 명령을 실행합니다.
ExecuteXMLReader XmlReader를 반환합니다. SqlCommand 개체에만 사용할 수 있습니다.

강력한 형식의 각 명령 개체는 명령 문자열의 해석 방법을 지정하는 CommandType 열거형도 지원합니다. 다음 표에는 CommandType의 각 열거형이 나와 있습니다.

CommandType 설명
Text 데이터 소스에 실행할 문을 정의하는 SQL 명령입니다.
StoredProcedure 저장 프로시저의 이름입니다. 호출하는 Parameters 메서드에 관계없이 명령의 Execute 속성을 사용하면 입력 및 출력 매개 변수와 반환 값에 액세스할 수 있습니다.
TableDirect 테이블의 이름입니다.

중요

ExecuteReader를 사용하는 경우 DataReader가 닫히기 전에는 반환 값과 출력 매개 변수에 액세스할 수 없습니다.

예시

다음 코드 예제에서는 SqlCommand 개체를 만든 다음 해당 속성을 설정하여 저장 프로시저를 실행하는 방법을 보여 줍니다. 저장 프로시저에 대한 입력 매개 변수를 지정하는 데는 SqlParameter 개체를 사용합니다. ExecuteReader 메서드를 사용하여 명령을 실행하고 SqlDataReader의 출력을 콘솔 창에 표시합니다.

static void GetSalesByCategory(string connectionString,
    string categoryName)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        // Create the command and set its properties.
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandText = "SalesByCategory";
        command.CommandType = CommandType.StoredProcedure;

        // Add the input parameter and set its properties.
        SqlParameter parameter = new SqlParameter();
        parameter.ParameterName = "@CategoryName";
        parameter.SqlDbType = SqlDbType.NVarChar;
        parameter.Direction = ParameterDirection.Input;
        parameter.Value = categoryName;

        // Add the parameter to the Parameters collection.
        command.Parameters.Add(parameter);

        // Open the connection and execute the reader.
        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader())
        {
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
                }
            }
            else
            {
                Console.WriteLine("No rows found.");
            }
            reader.Close();
        }
    }
}

명령 문제 해결

SQL Server용 Microsoft SqlClient 데이터 공급자는 실패한 명령 실행과 관련된 간헐적인 문제를 감지할 수 있도록 진단 카운터를 추가합니다. 자세한 내용은 SqlClient의 진단 카운터를 참조하세요.

참고 항목