jams jams - 2 years ago 66
SQL Question

How to return a table from a Stored Procedure?

It is very simple question.

I am trying to return a table from a stored procedure, like

select * from emp where id=@id

I want to return this query result as a table. I have to do this through a stored procedure.

Answer Source

Where is your problem??

For the stored procedure, just create:

   SELECT *  -- I would *strongly* recommend specifying the columns EXPLICITLY
   FROM dbo.Emp
   WHERE ID = @EmpID

That's all there is.

From your ASP.NET application, just create a SqlConnection and a SqlCommand (don't forget to set the CommandType = CommandType.StoredProcedure)

DataTable tblEmployees = new DataTable();

using(SqlConnection _con = new SqlConnection("your-connection-string-here"))
using(SqlCommand _cmd = new SqlCommand("ReadEmployees", _con))
    _cmd.CommandType = CommandType.StoredProcedure;

    _cmd.Parameters.Add(new SqlParameter("@EmpID", SqlDbType.Int));
    _cmd.Parameters["@EmpID"].Value = 42;

    SqlDataAdapter _dap = new SqlDataAdapter(_cmd);


YourGridView.DataSource = tblEmployees;

and then fill e.g. a DataTable with that data and bind it to e.g. a GridView.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download