Executing Queries That Use COMPUTE BY

Problem

The SQL Server .NET data provider does not support the COMPUTE BY clause but you want to execute a COMPUTE BY statement using ADO.NET.

Solution

Use the COMPUTE BY statement from the Command object of the OLE DB .NET data provider.

The sample code defines a COMPUTE BY statement and executes it using the ExecuteReader( ) method of the OleDbCommand object. Multiple result sets are returned by the DataReader and then these are displayed.

The C# code is shown in Example 3-13.

Example 3-13. File: ComputeForm.cs

// Namespaces, variables, and constants
using System;
using System.Text;
using System.Data;
using System.Data.OleDb;

// . . . 

StringBuilder result = new StringBuilder( );

String sqlSelect = "select OrderID, ProductID, Quantity " +
 "FROM [Order Details] " +
 "ORDER BY ProductID " +
 "COMPUTE SUM(quantity) by ProductID";

OleDbConnection conn = new OleDbConnection(
 ConfigurationSettings.AppSettings["OleDb_Shape_ConnectString"]);
OleDbCommand cmd = new OleDbCommand(sqlSelect, conn);
conn.Open( );

OleDbDataReader dr = cmd.ExecuteReader( );

do
{
 result.Append("Order	Product	Quantity" + Environment.NewLine);
 while(dr.Read( ))
 {
 result.Append(dr.GetInt32(0) + "	" + dr.GetInt32(1) + "	" +
 dr.GetInt16(2) + Environment.NewLine);
 } 

 // Get the sum.
 dr.NextResult( );
 dr.Read( );
 result.Append("SUM		" + dr.GetInt32(0) + Environment.NewLine);
 result.Append(Environment.NewLine);
} while(dr.NextResult( ));

dr.Close( );
conn.Close( );

resultTextBox.Text = result.ToString( );

Discussion

The SQL Server .NET data provider does not support the COMPUTE BY clause, but the OLE DB .NET data provider does. The results are returned as multiple pairs of result sets, the first of which contains the selected details and the second containing the results of the aggregate functions specified (the sum of the quantity ordered for the product in this example) in the COMPUTE BY clause. This pattern is repeated for the remaining pairs of result sets.

Microsoft states that the COMPUTE and COMPUTE BY clauses are provided in SQL Server 7.0 and later versions for backward compatibility. The ROLLUP operator provides similar functionality and is recommended instead. The main difference is that ROLLUP returns a single result set instead of multiple result sets. For more information about the ROLLUP operator, see Microsoft SQL Server Books Online.

Connecting to Data

Retrieving and Managing Data

Searching and Analyzing Data

Adding and Modifying Data

Copying and Transferring Data

Maintaining Database Integrity

Binding Data to .NET User Interfaces

Working with XML

Optimizing .NET Data Access

Enumerating and Maintaining Database Objects

Appendix A. Converting from C# to VB Syntax



ADO. NET Cookbook
ADO.NET 3.5 Cookbook (Cookbooks (OReilly))
ISBN: 0596101406
EAN: 2147483647
Year: 2002
Pages: 222
Authors: Bill Hamilton

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net