如何从存储过程返回记录集合并将结果输入到c#代码?

时间:2014-07-16 04:29:58

标签: c# sql sql-server

我有一个名为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))

此过程返回多个记录

示例O / P:

a_code
------    
 10004 
 10002 
 10003 
 10006

如何从存储过程返回这些行以及如何在C#代码中获取此返回值?

2 个答案:

答案 0 :(得分:1)

试试这个:

        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();
        }

答案 1 :(得分:0)

如果您正在使用.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
    }

现在你有了一个简单的MyAddressObject列表,你可以用它做什么!