Out of curiosity and the eternal hunger for more insight :)
There's this CLR stored procedure here which sends results back to the client through the following code. An array of SqlMetaData is attached to SqlDataRecord. Each SqlDataRecord gets values which are sent to clients through a pipe.
SqlMetaData[] columns = new SqlMetaData[1];
columns[0] = new SqlMetaData("bool", SqlDbType.Bit);
SqlDataRecord record = new SqlDataRecord(columns);
SqlContext.Pipe.SendResultsStart(record);
foreach (bool b in bools)
{
record.SetBoolean(0, b);
SqlContext.Pipe.SendResultsRow(record);
}
SqlContext.Pipe.SendResultsEnd();
client code:
SqlCommand cmd = new SqlCommand("CLR_SPROC", connection)
SqlDataReader reader = cmd.ExecuteReader();
int b = reader.GetOrdinal("bool"); // b == 0 because it was added in index 0 in the SqlMetaData array
So the ordinal of "bool" becomes zero as its found first in the first index. Interesting.
Now the question:
Does SqlServer work like this under the hood for every query? I mean when a query is executed, does the query parser extract the column names in the final select, builds up an SqlMetaData array from that, attaches that to an SqlDataRecord and sends it back over a stream?
So the query "SELECT a,b,c FROM table"
becomes
SqlMetaData[] columns = new SqlMetaData[3];
columns[0] = new SqlMetaData("a", SqlDbType.Int);
columns[1] = new SqlMetaData("b", SqlDbType.Int);
columns[2] = new SqlMetaData("c", SqlDbType.Int);
SqlDataRecord record = new SqlDataRecord(columns);
SqlContext.Pipe.SendResultsStart(record);
foreach(...)
{
record.SetInt32(0, a);
record.SetInt32(1, b);
record.SetInt32(2, c);
SqlContext.Pipe.SendResultsRow(record);
}