MARS
MARS stands for Multiple Active Result Sets. This is
introduced for SQL server 2005 with ADO.net 2.0. MARS means, it will allow us to
execute multiple queries, SP’s in a single open DB connection i.e. we can
execute multiple DataReader object with single database connection.
In 1.x days, we will get following error when we do the
above execution,
“There is already an open DataReader associated with this
Command which must be closed first.”
ADO.Net 2.0 answers this by introducing MARS.
How to achieve this?
By default, MARS is not enabled in SQL server 2005 we
need to do this by setting the following attribute in connection string,
MultipleActiveResultSets=True
Usage
The following code uses 2 Datareader with different
queries and it uses a single connection object. There are 2 tables Employees and
EmpDesignation in the database which are related,
string connectionString = @"Data
Source=BabuLives\SQLEXPRESS;Integrated Security=SSPI;Initial
Catalog=master;MultipleActiveResultSets=True";
int empID;
SqlDataReader desigReader = null;
string empSQL ="Select * from Employees";
string desigSQL = "Select Designation from
empDesignation where empid = @employeeid";
using (SqlConnection awConnection =
new SqlConnection(connectionString))
{
SqlCommand empCmd = new SqlCommand(empSQL,
awConnection);
SqlCommand desigCmd = new SqlCommand(desigSQL,
awConnection);
desigCmd.Parameters.Add("@employeeid",
SqlDbType.Int);
awConnection.Open();
using (SqlDataReader empReader =
empCmd.ExecuteReader())
{
while (empReader.Read())
{
Response.Write(empReader["EMPName"] +"
is ");
empID = (int)empReader["EMPId"];
//desigCmd.Parameters["@employeeid"].Value = vendorID;
// The following line of code
requires
// a MARS-enabled connection.
desigCmd.Parameters["@employeeid"].Value = empID;
desigReader =
desigCmd.ExecuteReader();
using (desigReader)
{
while (desigReader.Read())
{
Response.Write(" " +
desigReader["Designation"].ToString());
}
Response.Write("<br>");
}
}
}
}
The output will be,
Satheesh is SE Ram is SSE senthil is Team
Lead kumar is Iteration manager sabari is Project Manager
|