18

When I call this code:

using (var connection = new SqlConnection(connectionString))
{
    var command = new SqlCommand("SELECT * FROM Table", connection);
    connection.Open();
    using (var reader = command.ExecuteReader())
    {
        while(reader.Read())
        {
            // Do something here
        }
    }
}

what happens internally? How does this work on a network level? Will it make a new round trip to database for each call to Read or is there any batch read implemented internally?

I'm asking because I just read that ODP.NET provides FetchSize property in both OracleCommand and OracleDataReader which I understand as definition of how many records should be preloaded by single round trip to the database. I wonder if SQL Server works in similar fashion and if there is some similar behavior which can be configured somewhere. I didn't find any such configuration in SqlCommand, SqlDataReader or CommandBehavior.

Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654

2 Answers2

11

the data is streamed from sql server to the client in the packets of the size in SqlConnection.PacketSize property. If your client can't read results fast enough the buffer on the network card gets filled up, the protocol detects this and stops receiving which in turn makes sql server's network card send buffer full and it stops sending any and all data. if you want to go down to the protocl level then check out TDS protcol.

Mladen Prajdic
  • 15,018
  • 2
  • 39
  • 48
  • I did [**this test**](http://i.imgur.com/K6IogT2.png) , but if i set packetsize to smallest value ( negative ?) - would it show me 1,7,7,7,7, instead of 1,2,3,4,5,6 ? – Royi Namir Nov 29 '14 at 20:45
  • It seems TDS is an MS protocol. Oracle's respective seems to be "Oracle Net Services" – LucaSC Apr 05 '19 at 17:29
2

I believe the exact details of the network communications are dependent on a lot of things outside of your code sample, in part because of the SQL Server Connection Pooling, but I think you're looking for the SqlConnection.PacketSize property (MSDN).

chezy525
  • 3,777
  • 6
  • 24
  • 39