上篇讲了在即时消息系统中如何控制线程事件 这次讲讲C#中如何调用存储过程。登峰之道的原则是尽量用简短的代码说明问题:)
1。在SQL SERVER中的相应存储过程
CREATE PROCEDURE sp_test @ln varchar(10) , @msg varchar(80) output
AS
declare @flag int
declare @un varchar(80)
set @flag=99
select @un= username from msg_userinfo where LoginName=@ln
set @msg="this message from sp_test:"
select @msg =+@msg+@un
return @flag
GO
2.C#调用存储过程
private void TestSP()
{
SqlCommand _cmd=new SqlCommand();
DbBase db=DbBase.GetInstance();
_cmd.Connection=db.conn;
_cmd.CommandType=CommandType.StoredProcedure;
_cmd.CommandText="sp_test";// SQL Server Procedure Name
//输入登录名
SqlParameter un=new SqlParameter();
un.ParameterName="@ln";
un.DbType=DbType.String;
un.Direction=ParameterDirection.Input;
un.SourceVersion=DataRowVersion.Current;
_cmd.Parameters.Add(un);
_cmd.Parameters["@ln"].Value="zsb";
//RETURN_VALUE parameter
SqlParameter _RETURN_VALUE=new SqlParameter();
_RETURN_VALUE.ParameterName="@RETURN_VALUE";
_RETURN_VALUE.DbType=DbType.Int32;
_RETURN_VALUE.Direction=ParameterDirection.ReturnValue;
_RETURN_VALUE.SourceVersion=DataRowVersion.Current;
_cmd.Parameters.Add(_RETURN_VALUE);
//Return Message
SqlParameter outpara=new SqlParameter();
outpara = new SqlParameter("@msg", SqlDbType.VarChar,100);
outpara.Direction = ParameterDirection.Output;
_cmd.Parameters.Add(outpara);
_cmd.ExecuteNonQuery();
Console.WriteLine((int) _cmd.Parameters["@RETURN_VALUE"].Value);
Console.WriteLine(_cmd.Parameters["@msg"].Value.ToString());
//UserName parameter
}