I created a stored procedure so as to return me a table.
Something like this:
create procedure sp_returnTable body of procedure select * from table end
When I call this stored procedure on the frontend what code do I need to write to retrieve it in a datatable object?
I wrote code something like the following. I basically want to know retrieving and storing table into an object of datatable. All my queries are running, but I don't know how to retrieve table into a datatable through a stored procedure
DataTable dtable = new DataTable(); cmd.Connection = _CONN; cmd.CommandText = SPNameOrQuery; cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter adp = new SqlDataAdapter(cmd); OpenConnection(); adp.Fill(dtTable); CloseConnection();
Here in this code a command has been bound with the stored procedure name and its parameters. Will it be returning me a datatable from the stored procedure?
CommandText property to the name of the stored procedure. Execute the command by calling the OACommand. ExecuteReader method. The final step is to materialize the result.
The RETURN exits the stored procedure, and nothing that follows it will be executed, including the SELECT statement on the following line. Otherwise, if you want the data for the entire table, as your question shows, add a SELECT after the INSERT . But don't put RETURN in front of it!
We can pass the DataTable to the Stored Procedure using ADO.Net in the same way as we provided using the System. Data. SqlParameter class, but needs a few changes in the datatype. Normally we provide DbType of SqlParameter for a normal parameter like varchar, nvarchar, int and so on as in the following code.
string connString = "<your connection string>"; string sql = "name of your sp"; using(SqlConnection conn = new SqlConnection(connString)) { try { using(SqlDataAdapter da = new SqlDataAdapter()) { da.SelectCommand = new SqlCommand(sql, conn); da.SelectCommand.CommandType = CommandType.StoredProcedure; DataSet ds = new DataSet(); da.Fill(ds, "result_name"); DataTable dt = ds.Tables["result_name"]; foreach (DataRow row in dt.Rows) { //manipulate your data } } } catch(SQLException ex) { Console.WriteLine("SQL Error: " + ex.Message); } catch(Exception e) { Console.WriteLine("Error: " + e.Message); } }
Modified from Java Schools Example
Set the CommandText
as well, and call Fill
on the SqlAdapter
to retrieve the results in a DataSet
:
var con = new SqlConnection(); con.ConnectionString = "connection string"; var com = new SqlCommand(); com.Connection = con; com.CommandType = CommandType.StoredProcedure; com.CommandText = "sp_returnTable"; var adapt = new SqlDataAdapter(); adapt.SelectCommand = com; var dataset = new DataSet(); adapt.Fill(dataset);
(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With