ASP.NET执行存储过程,并获取存储过程的返回值

    一个简单例子如下:

      1、创建存储过程(用于用户身份验证):

      Create Procedure CheckUser
    (
     @userid char(20),
     @userpsw char(20)
     )
    as
     if exists(select * from tb_UserInfo where rtrim(UserID)=@userid and rtrim(UserPsw)=@userpsw)
      return 1
     else
      return 0

     2、Asp.net执行代码:

        //连接数据库
        string myStr = ConfigurationManager.AppSettings["connectionstring"].ToString();
        SqlConnection myConn = new SqlConnection(myStr);
        myConn.Open();

        //创建SqlCommand对象
        SqlCommand cmd = new SqlCommand("CheckUser",myConn);
        cmd.CommandType = CommandType.StoredProcedure;
       

        //添加参数
        SqlParameter Userid = cmd.Parameters.Add("@Userid", SqlDbType.Char);
        SqlParameter Userpsw= cmd.Parameters.Add("@Userpsw", SqlDbType.Char);
        SqlParameter returnvalue = cmd.Parameters.Add("@returnvalue", SqlDbType.Int);
        
        //指定参数是只可输入(Input)、输出(Output)还是返回值(ReturnValue)
        Userid.Direction = ParameterDirection.Input;
        Userpsw.Direction = ParameterDirection.Input;
        returnvalue.Direction = ParameterDirection.ReturnValue;
        
        //为传递给存储过程的参数赋值
        Userid.Value =tbUserName.Text.Trim();
        Userpsw.Value = tbPsw.Text.Trim();

        //执行SQL存储过程
        cmd.ExecuteNonQuery();

        //得到并判断返回值
        if ((int)returnvalue.Value == 1)
        {
            Session["user"] = tbUserName.Text.Trim();
            Response.Write("当前用户:" + Session["user"]);
        }
        else
        {
            Response.Write("用户不存在!");
        }

 

posted @ 2009-03-25 11:56  锐意  阅读(3294)  评论(0编辑  收藏  举报