Execute multiple SQL statements using DataReader - ADO.NET

Q.  How do you execute multiple SQL statements using a DataReader?
- Published on 27 Jul 15

a. Call the ExecuteReader method of a single Command object twice.
b. Set the Command.CommandText property to multiple SQL statements delimited by a semicolon.
c. Set the Command.CommandType property to multiple result sets.
d. None of the above.

ANSWER: Set the Command.CommandText property to multiple SQL statements delimited by a semicolon.
 

    Discussion

  • Ramesh   -Posted on 19 Oct 15
    You can execute more than one sql statement by using Command.CommandText property to multiple SQL statements delimited by a semicolon. In this situation you must use NextResult() method of datareader.
    Example:
    string sql=”select * from table1; select * from table2”;
    SqlConnection conObj=new SqlConnection(“provide your connection string”);
    SqlCommand cmdObj=new SqlCommand ();
    conObj.Open();
    SqlDataReader dr=cmdObj.ExecuteReader();

    While(dr.read())
    {
    // Process the table1
    }
    dr.NextResult();

    While(dr.read())
    {
    // Process the table2

    }

Post your comment / Share knowledge


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)