.net中执行存储过程以及参数设置
con.Open();
SqlCommand cmd = new SqlCommand("delete_CarInfo", con); //存储过程delete_Carinfo
cmd.CommandType = CommandType.StoredProcedure; //指定Command命令执行类型
SqlParameter sp_1 = new SqlParameter("@CarID_1", SqlDbType.VarChar, 20);
//指定存储过程的执行时的参数
sp_1.Value = Car_ID;
cmd.Parameters.Add(sp_1);
cmd.ExecuteNonQuery();
con.Close();
*************************************************************************************************
执行存储过程的返回值:
因为一般都用T-SQL来执行数据库操作,偶尔现在转到用存储过程,竟然写不来调用过程的返回值了,查了很多资料,都不详细,或者没到点上,也许是我比较笨,呵呵。
C# 源代码
1 /// <summary>
2 /// 校验用户
3 /// </summary>
4 /// <param name="user">用户信息</param>
5 /// <returns></returns>
6 public static int VerifyUser(clsUser user)
7 {
8 int iRet;
9 string sql = String.Format("EXECUTE VerifyUser @myVerifyReader OUTPUT,'{0}','{1}'",user.username,user.password); //执行的T-SQL串
10 SqlCommand scmd = new SqlCommand(sql, conn);
11 scmd.Parameters.Add(new SqlParameter("@myVerifyReader",SqlDbType.Int));
12 scmd.Parameters["@myVerifyReader"].Direction = ParameterDirection.Output;
13 //
14
15 DBOpen(conn);
16 //在返回值上有问题
17 scmd.ExecuteNonQuery();
18 iRet = (int)scmd.Parameters["@myVerifyReader"].Value;
19 DBClose(conn);
20 return iRet;
21 }
2 /// 校验用户
3 /// </summary>
4 /// <param name="user">用户信息</param>
5 /// <returns></returns>
6 public static int VerifyUser(clsUser user)
7 {
8 int iRet;
9 string sql = String.Format("EXECUTE VerifyUser @myVerifyReader OUTPUT,'{0}','{1}'",user.username,user.password); //执行的T-SQL串
10 SqlCommand scmd = new SqlCommand(sql, conn);
11 scmd.Parameters.Add(new SqlParameter("@myVerifyReader",SqlDbType.Int));
12 scmd.Parameters["@myVerifyReader"].Direction = ParameterDirection.Output;
13 //
14
15 DBOpen(conn);
16 //在返回值上有问题
17 scmd.ExecuteNonQuery();
18 iRet = (int)scmd.Parameters["@myVerifyReader"].Value;
19 DBClose(conn);
20 return iRet;
21 }
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
/*
* 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