Running Totals: SQLCLR version
Riprendo il post "Running totals: cursori, complessità lineari, complessità esponenziali" per presentare una terza soluzione basata su SQLCLR, ovvero tramite una stored procedure costruita ad hoc e, quindi, verificarne le performance.
Questo il codice C#:
[SqlProcedure]
public static void up_runningTotals()
{
string tsqlStatement = "SELECT customerID, qty, 0 AS qtySum FROM orders ORDER BY customerID";
SqlConnection cn = new SqlConnection("context connection=true");
cn.Open();
SqlCommand cmd = new SqlCommand(tsqlStatement, cn);
SqlPipe myPipe = SqlContext.Pipe;
SqlDataRecord record = new SqlDataRecord
(
new SqlMetaData("customerID", SqlDbType.Char,1),
new SqlMetaData("qty", SqlDbType.Int),
new SqlMetaData("qtySum", SqlDbType.Int)
);
string myCustomerID = "";
Int32 myQtySum = 0;
SqlDataReader dr = cmd.ExecuteReader();
myPipe.SendResultsStart(record);
if (dr.HasRows)
{
while (dr.Read())
{
if (myCustomerID != dr["customerID"].ToString())
myQtySum = 0;
myCustomerID = dr["customerID"].ToString();
myQtySum += Convert.ToInt32(dr["qty"]);
record.SetValue(0, Convert.ToChar(dr["customerID"]));
record.SetInt32(1, Convert.ToInt32(dr["qty"]));
record.SetInt32(2, myQtySum);
myPipe.SendResultsRow(record);
}
}
myPipe.SendResultsEnd();
dr.Close();
cmd.Dispose();
cn.Dispose();
}
Questi i risultati sulla mia macchina:
| Num Record |
Soluzione TSQL |
Soluzione cursore |
Soluzione SQLCLR |
| 30 |
0 |
106 |
10 |
| 300 |
30 |
96 |
203 |
| 3000 |
1160 |
513 |
250 |
| 30000 |
53060 |
2643 |
1030 |
Risultati interessanti, no?