.Net 中使用存储过程

      My Works 2007-1-22 11:3

建一存储过程:

CREATE PROCEDURE dbo.testProcedure_AX
AS
select userID from USERS order by userid desc

C#中:

   public static string GetCustomerCName(ref ArrayList arrayCName,ref ArrayList arrayID)
        {
            SqlConnection con=ADConnection.createConnection();
            SqlCommand cmd=new SqlCommand("testProcedure_AX",con);
            cmd.CommandType=CommandType.StoredProcedure;
            con.Open();
            try
            {
                SqlDataReader dr=cmd.ExecuteReader();
                while(dr.Read())
                {
                    if(dr[0].ToString()=="")
                    {
                        arrayCName.Add(dr[1].ToString());
                    }
                }
                con.Close();
                return "OK!";
            }
            catch(Exception ex)
            {
                con.Close();
                return ex.ToString();
            }
        }
注:其实就是把以前
SqlCommand cmd=new SqlCommand("select userID from USERS order by userid desc",con);
中的SQL语句替换为存储过程名,再把cmd的类型标注为CommandType.StoredProcedure(存储过程)

带参数的存储过程

CREATE PROCEDURE dbo.AXzhz
/*
这里写注释
*/
@startDate varchar(16),
@endDate varchar(16)
AS
 select id  from table_AX where commentDateTime>@startDate and commentDateTime<@endDate order by contentownerid DESC

注:@startDate varchar(16)是声明@startDate 这个变量,多个变量名间用【,】隔开.后面的SQL就可以使用这个变量了.

⑥在ASP.NET中调用这个带参数的存储过程

 public static string GetCustomerCNameCount(string startDate,string endDate,ref DataSet ds)
{
            SqlConnection con=ADConnection.createConnection();
//-----------------------注意这一段--------------------------------------------------------------------------------------------------------
            SqlDataAdapter da=new SqlDataAdapter("AXzhz",con);

            para0=new SqlParameter("@startDate",startDate);
            para1=new SqlParameter("@endDate",endDate);
            da.SelectCommand.Parameters.Add(para0);
            da.SelectCommand.Parameters.Add(para1);
            da.SelectCommand.CommandType=CommandType.StoredProcedure;
//-------------------------------------------------------------------------------------------------------------------------------


            try
            {
                con.Open();
                da.Fill(ds);
                con.Close();
                return "OK";
            }
            catch(Exception ex)
            {
                return ex.ToString();
            }           
        }

标签集:TAGS:
回复Comments() 点击Count()

回复Comments

{commenttime}{commentauthor}

{CommentUrl}
{commentcontent}