Search code examples
c#sql-serverstored-proceduressqlexception

SqlException in c#


I have a function that calls a stored procedure. But it throws an exception some thing like this :

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid column name 'quantity'.

Invalid column name 'quantity'.
Invalid column name 'location'.
Invalid column name 'quantity'.
Invalid column name 'quantity'.
Invalid column name 'quantity'. ...

I don't understand why this exception is thrown because the stored procedure works fine in MSSMS.

Here is my code for calling the stored procedure:

public DataSet getDataTable_sp(string sp_name, SqlParameter[] p = null)
{
            DataSet ds = new DataSet();

            using (SqlConnection conn = new SqlConnection(Connstr))
            {
                SqlDataAdapter da = new SqlDataAdapter(sp_name,conn);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                da.SelectCommand.CommandTimeout = 300;

                if (p != null)
                    for (int i = 0; i < p.Count(); i++)
                        da.SelectCommand.Parameters.Add(p[i].ParameterName, p[i].SqlDbType, p[i].Size).Value = p[i].Value;

                conn.Open();
                da.Fill(ds); // this is the line that the exception is thrown
                conn.Close();
            }

            return ds;
}

Solution

  • I have also encountered the same error before, I think the problem was on your stored procedure. Try to check all the declarations, specially your temporary tables. I don't know if it will works on your part. Try to avoid the same temporary tables name. Just try it :)