ERROR ON EXECUTING A STORED PROCEDURE USING WHILE CONDITION

Pravesh Singh

Total Post:412

Points:2888
Posted by  Pravesh Singh
C#
 945  View(s)
Ratings:
Rate this:

Hi Expert!

my line of code as below

SqlConnection sqlConn = new SqlConnection(MyClass.GlobalConn());
        sqlConn.Open();

        try
        {
            string getAllBranch = "SELECT iBranch_num,LTRIM(RTRIM(sConstant)) FROM tblgobranch";
            SqlCommand cmdgetAllBranch = new SqlCommand(getAllBranch, sqlConn);
            SqlDataReader dRgetAllBranch=cmdgetAllBranch.ExecuteReader();



            while (dRgetAllBranch.Read())
            {

                SqlCommand cmd = new SqlCommand("dbo.rvk_GetSalesPerItem", sqlConn);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add("@piDateFrom", SqlDbType.Int).Value = FromDT1;
                cmd.Parameters.Add("@piDateThru", SqlDbType.Int).Value = ToDT2;
                cmd.Parameters.Add("@BRANCH", SqlDbType.NVarChar).Value = dRgetAllBranch[1].ToString();
                cmd.Parameters.Add("@brNum", SqlDbType.Int).Value = dRgetAllBranch[0].ToString();
                cmd.Parameters.Add("@PluCode", SqlDbType.NVarChar).Value = str1;
                cmd.ExecuteNonQuery();

            }
I got error here

"There is already open data reader associated with this command"

Please help me with this.
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Error on executing a stored procedure using While condition

    Hi Pravesh!

    Try this way

    SqlConnection sqlConnStoredProc = new SqlConnection(MyClass.GlobalConn());
    sqlConnStoredProc.Open();

    SqlCommand cmd = new SqlCommand("dbo.rvk_GetSalesPerItem", sqlConnStoredProc);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.Add("@piDateFrom", SqlDbType.Int).Value = FromDT1;
    cmd.Parameters.Add("@piDateThru", SqlDbType.Int).Value = ToDT2;
    cmd.Parameters.Add("@BRANCH", SqlDbType.NVarChar).Value = dRgetAllBranch[1].ToString();
    cmd.Parameters.Add("@brNum", SqlDbType.Int).Value = dRgetAllBranch[0].ToString();
    cmd.Parameters.Add("@PluCode", SqlDbType.NVarChar).Value = str1;
    cmd.ExecuteNonQuery();

    sqlConnStoredProc.Close();

    I hope it resolve your problem

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!