第一种:无参的情况下
string str=" 连接字符串";
string sql="存储过程";//注意这里是直接的存储过程名称.
DataTable dt=new DataTable();
using(SqlDataAdapter sda=new SqlDataAdapter(sql,str)
{
sda.SelectCommand.CommandType=CommandType.StoreProcedure;//声明该语句为存储过程,注意这里不一定为selectcommand,主要看你的存储过程类型.
sda.Fill(dt);
}
关键字:SelectCommand
官方注解:获取或设置一个Transact-SQL语句或存储过程,用于在数据源中选中记录
StoreProcedure
官方注解:存储过程的名称.
CommandType
官方注解:获取或设置一个值,该值指示如何解释System.Data.SqlClient.SqlCommand.CommandText属性.
第二种:有参的情况
SqlParameter[] ps={
new SqlParameter("@name",value1)//这里的value指的具体的值.name是存储过程需要的参数,
new SqlParameter("@id",value2);
}
string str="连接字符串";
string sql="存储过程";
using(SqlConnction con=new SqlConnection(str))
{
using(SqlCommand cmd=new SqlCommand(sql,con))
{
con.open();
cmd.Parmeter.AddRange(ps);//添加参数数组
cmd.CommandType=CommandType.StoreProcedure;//设置类型为存储过程
cmd.ExecteNonQuery();
}
}
这里需要注解的是如果需要传入或者传出的参数,通过这样设置
ps[0].Direction=ParameterDirection.Output;//输出参数
ps[1].Direction=ParameterDirection.Input;//传入参数
SqlParamter.Direction
官方注解:获取或设置一个值,该值指示参数是只可输入,只可输出,双向还是存储过程返回值参数.
ParamterDirection
官方注解:指定查询内的有关System.Data.DataSet的参数的类型