简体   繁体   中英

How to Get Data from Stored Procedure in SQL Server

I read data from my stored procedure. When I insert a breakpoint I get this situation:

在此处输入图片说明

The stored procedure returns one row with 8 columns. You can see this on a picture. But when I am trying to read one value:

var post_id = reader[4].ToString();

I got this exception:

Invalid attempt to read when no data is present.

My model:

  public class Alarm
{
    public long Id { get; set; }
    public DateTime StartDate { get; set; }
    public int Snoozes { get; set; }
    public bool Repeat { get; set; }
    public DateTime AlarmUpdateTime { get; set; }

    public virtual User User { get; set; }
    public virtual List<FacebookNotificationStatus> StatusUpdates { get; set; }
}

public class FacebookStatusUpdate
{
    public long Id { get; set; }
    public DateTime FacebookUpdateTime { get; set; }
    public string PostId { get; set; }
    public DateTime? FacebookPostTime { get; set; }
    public DateTimeOffset ClientTime { get; set; }
    public int Offset { get; set; }

    public virtual FacebookNotificationStatus Status { get; set; }
    public virtual Alarm Alarm { get; set; }
}

Can somebody help me?

You need to call the reader.Read() before reading the records.

Example:

 String column1="";
 String column2="";
 while(reader.Read())
    {
      column1 = reader["column1"].ToString();
      column2 = reader["column2"].ToString();
    }

after executing command.ExecuteReader() you can loop through data with next code (just sample):

var rdr = command.ExecuteReader();
while(rdr.Read()) 
{
  var obj = new MyClass();
  obj.Id = (int)rdr["Id"];
  if (rdr["Name"] != DBNull.Value)
  {
    obj.name = (string)rdr["Name"];
  }
}
rdr.Close();

this sample reads all fetched data from DB row-by-row.

Also don't forget to read read SqlDataReader manual for more information how to work with readers.

Dealing with all the subtleties of ADO.NET is not fun; frankly, I suspect you might find it easier to use something like "dapper", which allows:

using(var conn = ...)
{
    return conn.Query<FacebookStatusUpdate>("GetPostList"),
       commandType: CommandType.StoredProcedure).ToList();
} 

(assuming that the column names are a direct match to the property names on FacebookStatusUpdate )

And for passing parameters:

string region = ...
DateTime minDate = ...
using(var conn = ...)
{
    return conn.Query<FacebookStatusUpdate>("GetPostList"),
       new { region, minDate },
       commandType: CommandType.StoredProcedure).ToList();
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM