第一步:在数据中编写好通过编号来获取当前学生的更多信息的存储过程(以学生表为主,暂时不展示数据)
---根据编号来查询出学生的其他信息,带输入输出参数
if(exists(select * from sys.objects where name = 'proc_getStudentOtherInfoBySid')) //判断当前数据库中是否存在这个存储过程
drop proc proc_getStudentOtherInfoBySid //如果存在就删除
go
create proc proc_getStudentOtherInfoBySid //重新创建这个存储过程
(
@sid int ,
@sname nvarchar(50) output,
@sage int output,
@saddress nvarchar(50) output,
@stelephone varchar(50) output
)
as
select @sname=sname ,@sage = sage,@saddress=saddress,@stelephone=stelephone from [dbo].[students] where sid=@sid
go
declare @sname nvarchar(50)
declare @sage int
declare @saddress nvarchar(50)
declare @stelephone varchar(50)
exec proc_getStudentOtherInfoBySid 1 , @sname output,@sage output ,@saddress output,@stelephone output
print @sname+''+convert(nvarchar(4),@sage)+' '+@saddress+' '+@stelephone //convert(转换的类型,需要转换的数据)
第二步:通过Ado.Net来调用当前的存储过程
string conn = "Data Source=.;Initial Catalog=justTest;Integrated Security=True";
int sid = 1;
using (SqlConnection connOpen = new SqlConnection (conn) )
{
connOpen.Open();
using (SqlCommand comm = new SqlCommand("proc_getStudentOtherInfoBySid", connOpen))
{
//设置调用类型是存储过程
comm.CommandType = System.Data.CommandType.StoredProcedure;
//设置存储过程所需要的参数
SqlParameter[] pataMeter = new SqlParameter[] {
new SqlParameter("@sid",System.Data.SqlDbType.Int ),
new SqlParameter("@sname",System.Data.SqlDbType.NVarChar,50),
new SqlParameter("@sage",System.Data.SqlDbType.Int),
new SqlParameter("@saddress",System.Data.SqlDbType.NVarChar,50),
new SqlParameter("@stelephone",System.Data.SqlDbType.VarChar,50)
};
//设置输入参数
pataMeter[0].Value = sid; //存储过程中已经设置好了这个参数,这里添加或者不添加都可以,对应上面构建参数的@sid(可以删除)
pataMeter[1].Direction= System.Data.ParameterDirection.Output;
pataMeter[2].Direction = System.Data.ParameterDirection.Output;
pataMeter[3].Direction = System.Data.ParameterDirection.Output;
pataMeter[4].Direction = System.Data.ParameterDirection.Output;
comm.Parameters.AddRange(pataMeter);
comm.ExecuteNonQuery();
Student student = new Student();
student.sname = comm.Parameters["@sname"].Value.ToString();
student.sgae = Convert.ToInt32(comm.Parameters["@sage"].Value);
student.saddress = comm.Parameters["@saddress"].Value.ToString();
student.stelephone = comm.Parameters["@stelephone"].Value.ToString();
Console.WriteLine(student.sname+"\t"+student.sgae+"\t"+student.saddress+"\t"+student.stelephone);
}
connOpen.Close();
}
Console.ReadKey();
备注:我把存储过程返回来的数据封装成为一个学生类来存储数据
/// <summary>
/// 构建学生类
/// </summary>
public class Student
{
public string sname { get; set; }
public int sgae { get; set; }
public string saddress { get; set; }
public string stelephone { get; set; }
}
--最终控制台效果和数据库中数据对比
}