How to return a table from a Stored Procedure?

后端 未结 3 738
死守一世寂寞
死守一世寂寞 2020-12-23 20:13

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 re

相关标签:
3条回答
  • 2020-12-23 20:48

    Where is your problem??

    For the stored procedure, just create:

    CREATE PROCEDURE dbo.ReadEmployees @EmpID INT
    AS
       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);
    
        _dap.Fill(tblEmployees);
    }
    
    YourGridView.DataSource = tblEmployees;
    YourGridView.DataBind();
    

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

    0 讨论(0)
  • 2020-12-23 20:52

    It's VERY important to include:

     SET NOCOUNT ON;
    

    into SP, In First line, if you do INSERT in SP, the END SELECT can't return values.

    THEN, in vb60 you can:

    SET RS = CN.EXECUTE(SQL)
    

    OR:

    RS.OPEN CN, RS, SQL
    
    0 讨论(0)
  • 2020-12-23 21:04

    In SQL Server 2008 you can use

    http://www.sommarskog.se/share_data.html#tableparam

    or else simple and same as common execution

    CREATE PROCEDURE OrderSummary @MaxQuantity INT OUTPUT AS
    
    SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
    FROM Orders AS Ord
         JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
    GROUP BY Ord.EmployeeID
    ORDER BY Ord.EmployeeID
    
    SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]
    
    RETURN (SELECT SUM(Quantity) FROM [Order Details])
    GO
    

    I hopes its help to you

    0 讨论(0)
提交回复
热议问题