Microsoft Docs

System.Data.CommandBehavior Enum

The CommandBehavior enumeration provides a set of flags that control the behavior of the command execution and data retrieval.

Namespace

System.Data

Assembly

System.Data.dll

Syntax

public enum CommandBehavior

Members

MemberValueDescription
Default0No special behavior.
SingleResult1Indicates that the command should return a single result set.
SchemaOnly2Retrieves only the schema without data.
KeyInfo4Retrieves primary key information.
SingleRow8Returns a single row from the result set.
SequentialAccess16Provides a forward-only, read-only stream of data.
CloseConnection32Closes the connection when the data reader is closed.

Examples

C#
VB.NET
using System;
using System.Data;
using System.Data.SqlClient;

class Example
{
    static void Main()
    {
        var connectionString = "Data Source=.;Initial Catalog=AdventureWorks;Integrated Security=True";
        using var connection = new SqlConnection(connectionString);
        var command = new SqlCommand("SELECT * FROM Production.Product", connection);
        connection.Open();

        using var reader = command.ExecuteReader(CommandBehavior.SchemaOnly);
        for (int i = 0; i < reader.FieldCount; i++)
        {
            Console.WriteLine($"{reader.GetName(i)} ({reader.GetFieldType(i).Name})");
        }
    }
}
Imports System
Imports System.Data
Imports System.Data.SqlClient

Module Example
    Sub Main()
        Dim connectionString As String = "Data Source=.;Initial Catalog=AdventureWorks;Integrated Security=True"
        Using connection As New SqlConnection(connectionString)
            Dim command As New SqlCommand("SELECT * FROM Production.Product", connection)
            connection.Open()

            Using reader As SqlDataReader = command.ExecuteReader(CommandBehavior.SchemaOnly)
                For i As Integer = 0 To reader.FieldCount - 1
                    Console.WriteLine($"{reader.GetName(i)} ({reader.GetFieldType(i).Name})")
                Next
            End Using
        End Using
    End Sub
End Module

Remarks

The CommandBehavior flags can be combined using a bitwise OR operation to tailor command execution to specific needs.