asp.net 常用的几种调用存储过程的方法

时间:2022-05-14 19:24:42

(1)简单的无参数存储过程
create procedure ExpOne
as
select top 10 * from Corp
go

C#调用此存储过程
        SqlConnection con = new SqlConnection(connstr);
        string procedurestr = "存储过程名";
        SqlCommand cmd = new SqlCommand(procedurestr, con);
        con.Open();
        cmd.CommandType = CommandType.StoredProcedure;
        i = cmd.ExecuteNonQuery();//这里是返回一个最后一次执行所影响的行数.
                                  //如果行数没有受影响,返回 -1.
        con.Close();

(2)通过存储过程使用隐式内联参数
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER procedure [dbo].[GetCorp]
@id int
as
select * from Corp where id=@id

C#中调用上面的存储过程
        SqlConnection con = new SqlConnection(connstr);  
        string sqltext = "存储过程名";
        SqlCommand cmd = new SqlCommand(sqltext, con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter p = new SqlParameter("@id", DbType.Int32);
        p.Direction = ParameterDirection.Input;
        p.Value = 1739;
        cmd.Parameters.Add(p);
        con.Open();
        SqlDataReader sdr = cmd.ExecuteReader();
        if (sdr.Read())
        {
            rtn = sdr["UserName"].ToString() + sdr["CorpName"].ToString() + sdr["Intro"].ToString();
       }
        sdr.Close();
        con.Close();
从上面代码可以看出,但参数个数非常多的时候其实也是非常麻烦的,目前还没有找到好的解决办法,大家可以使用参数数组,如果有更好的办法欢迎一起探讨.

SqlParameter[] p ={ new SqlParameter("@id", SqlDbType.Int, 4), new SqlParameter("@UserName", SqlDbType.NVarChar, 50) };
        p[0].Value = 1739;
        p[0].Direction = ParameterDirection.Input;
        p[1].Direction = ParameterDirection.Input;

foreach (SqlParameter pm in p)
       {
           cmd.Parameters.Add(pm);
        }

(3)通过存储过程调用显式的参数
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER procedure [dbo].[GetMyCorp]
@id int,@UserName nvarchar(50) output
as
select @UserName=UserName from t_jc_corp where id=@id
在asp.net 中调用该存储过程 得到输出参数 @UserName

SqlConnection con = new SqlConnection(connstr);
        con.Open();
        string procedurename = "GetMyCorp";
        SqlCommand cmd = new SqlCommand(procedurename, con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter p1 = new SqlParameter();
        p1 = cmd.Parameters.Add("@id",SqlDbType.Int,4);
        p1.Direction = ParameterDirection.Input;
        p1.Value = 1739;

SqlParameter p2 = new SqlParameter();
        p2 = cmd.Parameters.Add("@UserName", SqlDbType.NVarChar, 50);
        p2.Direction = ParameterDirection.Output;

SqlDataReader sdr = cmd.ExecuteReader();
        sdr.Close();
        rtn = p2.Value.ToString();