A
A
Alexey Lebedev2015-06-01 19:02:08
SQL
Alexey Lebedev, 2015-06-01 19:02:08

How to get 2 tables in a stored procedure in SQL Server?

This works great when one result is:

using (var comm = new SqlCommand("dbo.GetProfile", conn))
{
    comm.CommandType = CommandType.StoredProcedure;
    comm.Parameters.Add(new SqlParameter("@uid", uid));
    using (var reader = comm.ExecuteReader())
    {
        if (reader.Read())
        {
            Response.Write(reader["id"]);
            Response.Write(reader["level"]);
        }
    }
}

But when you need to get 2 tables, with a stored procedure like this:
ALTER PROCEDURE [dbo].[GetProfile]
@uid int
AS
BEGIN
    SET NOCOUNT ON;
  SELECT TOP 1 * FROM dbo.users where [email protected];
  SELECT * FROM locations;
END

4ccf9ba4793e4bacb5b0b87a4328ec01.png
How to do it? Is this a normal approach or is it better to split it into 2 procedures and 2 requests.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Lastochkin, 2015-06-01
@swanrnd

...
        if (reader.Read())
        {
            Response.Write(reader["id"]);
            Response.Write(reader["level"]);
        }

        var ok = reader.NextResult(); // <---

        if( !ok ) return;

        if (reader.Read())
        {
            Response.Write(reader["lid"]);
            Response.Write(reader["sublid"]);
        }
...

S
Stanislav Makarov, 2015-06-01
@Nipheris

What is the purpose of using a stored procedure just to retrieve data? I understand that you would make requests for modification with the addition of logic in order to do all this on the database side, but why fetch? If there are specific reasons, indicate, and we will think about how best to do it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question