interviews.dotnetthread.com

↑ Grab this Headline Animator

Sunday, October 19, 2008

How to read data from two tables in DataBase using SQL DataReader object.

We can mention two select statements in the command text for command object of SqlDataReader. Then execute the reader.

SqlCommand sqlComm = new SqlCommand("Select * from Table1; Select * from Table2");
SqlDataReader sqlDR = new SqlDataReader();
sqlDR = sqlComm.ExecuteReader(CommandBehavior.CloseConnection);

To read data from two table write code as below where we will read two result sets using while loops.

while(sqlDR.NextResult())
{
while(sqlDR.read())
{
// Your Code Here
}
}

Note: Dont forget to close DataReader after using in finally block. Especially when we are passing reader to other layer, So as to close connection attached to Reader and avoid in connection leaks(As we are using CommandBehavior.CloseConnection connection attached to Reader will be closed when reader is closed). Or better to use using statement.

Submit this story to DotNetKicks

No comments:

Post a Comment

Post your comments/questions/feedback for this Article.

 

Latest Articles