[英]How to return collection of record from stored procedure and get result in to c# code?
I have stored procedure called uspGetAddress
: 我已经存储了名为uspGetAddress
过程:
ALTER PROCEDURE [dbo].[uspGetAddress] @sdate dateTime,@edate dateTime
AS
(select a_code
from cust_personal
where c_no in (Select c.c_no
from a_basic a
INNER JOIN cust_personal b ON a.a_code = b.a_code
INNER JOIN cust_installment c ON b.c_no = c.c_no
where c.idate BETWEEN @sdate AND @edate))
This procedure returns multiple records 此过程返回多个记录
Example O/P: 示例O / P:
a_code
------
10004
10002
10003
10006
How to return these rows from the stored procedure and how to get this returned values in C# code? 如何从存储过程返回这些行,以及如何在C#代码中获取此返回值?
try this : 尝试这个 :
using (var connection = new SqlConnection("connectionstringHere"))
{
var cmd = connection.CreateCommand();
cmd.CommandText = "uspGetAddress"
cmd.Parameters.Add(new SqlParameter() { ParameterName = "@sdate" , SqlDbType = SqlDbType.DateTime , Value = DateTime.Now /* bind your value*/});
cmd.Parameters.Add(new SqlParameter() { ParameterName = "@edate" , SqlDbType = SqlDbType.DateTime , Value = DateTime.Now /* bind your value*/});
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection.Open();
var reader = cmd.ExecuteReader();
while(reader.Read()){
//do your work,
}
cmd.Connection.Close();
cmd.Dispose();
connection.Close();
connection.Dispose();
}
If you're using .Net Framework 3.5 or newer try this... 如果您使用的是.Net Framework 3.5或更高版本,请尝试此...
public class MyAddressObject
{
public int a_code { get; set; }
}
public static List<MyAddressObject> GetAddresses(DateTime dtStart, DateTime dtEnd)
{
#region Create SqlCommand
SqlCommand cmd;
cmd = new SqlCommand("[dbo].[uspGetAddress]");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@sdate", dtStart);
cmd.Parameters.AddWithValue("@edate ", dtEnd);
#endregion
#region Talk to the Database
DataSet objDataSet;
using (System.Data.SqlClient.SqlConnection objConn = new System.Data.SqlClient.SqlConnection(
"My Connection String"))
{
cmd.Connection = objConn;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
objDataSet = new DataSet();
da.Fill(objDataSet);
}
}
#endregion
#region Turn the data into a list of MyAddressObjects
var objResult = from data in objDataSet.Tables[0].AsEnumerable()
select new MyAddressObject
{
a_code = data.Field<int>("a_code")
};
return objResult.ToList();
#endregion
}
Now you have a simple List of MyAddressObject that you can do with what you will! 现在,您有了一个简单的MyAddressObject列表,可以使用您将要执行的操作!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.