C#调用存储过程返回值,因为一般都用T-SQL来执行数据库操作,偶尔现在转到用存储过程,竟然写不来调用过程的返回值了,查了很多资料,都不详细,或者没到点上,也许是我比较笨,呵呵。
C# 源代码
------------------------------
/// <summary>
/// 校验用户
/// </summary>
/// <param name="user">用户信息</param>
/// <returns></returns>
public static int VerifyUser(clsUser user)
{
int iRet;
string sql = String.Format("EXECUTE VerifyUser @myVerifyReader OUTPUT,'{0}','{1}'",user.username,user.password); //执行的T-SQL串
SqlCommand scmd = new SqlCommand(sql, conn);
scmd.Parameters.Add(new SqlParameter("@myVerifyReader",SqlDbType.Int));
scmd.Parameters["@myVerifyReader"].Direction = ParameterDirection.Output;
//
DBOpen(conn);
//在返回值上有问题
scmd.ExecuteNonQuery();
iRet = (int)scmd.Parameters["@myVerifyReader"].Value;
DBClose(conn);
return iRet;
}
SQL SERVER存储过程
------------------------------
/*
* VerifyUser 存储过程
* 用途:验证用户登陆
*/
CREATE PROCEDURE VerifyUser
(
@myVerifyReader int OUTPUT, --返回结果
@username varchar(50), --用户名
@userpassword varchar(50) --用户密码
)
AS
IF EXISTS(SELECT [id] FROM [Users] WHERE username = @username AND userpassword = @userpassword)
SET @myVerifyReader = 0 --通过验证
ELSE IF EXISTS(SELECT [id] FROM [Users] WHERE username = @username)
SET @myVerifyReader = 1 --用户存在,密码不正确
ELSE
SET @myVerifyReader = 2 --用户不存在
RETURN isnull(@myVerifyReader,3)
-------------------------------------------------
GO