sql server中编写一个存储过程:
- CREATE PROCEDURE ProGetPWD
- @username varchar(20),
- @password varchar(20) OUTPUT
- AS
- BEGIN
- SELECT @password = password
- FROM Users
- WHERE username = @username
- END
--------------------------
下面是.NET中调用存储过程的方法:
- string strConnection = "user id=sa;password=sa;initial catalog=MyTest;Server=YHB;Connect Timeout=30";
- using (SqlConnection conn = new SqlConnection(strConnection))
- {
- conn.Open();
- using (SqlCommand sqlComm = conn.CreateCommand())
- {
- //设置要调用的存储过程的名称
- sqlComm.CommandText = "GetPWD";
- //指定SqlCommand对象传给数据库的是存储过程的名称而不是sql语句
- sqlComm.CommandType = CommandType.StoredProcedure;
- SqlParameter username = sqlComm.Parameters.Add(new SqlParameter("@username", SqlDbType.VarChar, 20));
- //指明"@username"是输入参数
- username.Direction = ParameterDirection.Input;
- //为“@username”参数赋值
- username.Value = this.txt_username.Text;
- SqlParameter password = sqlComm.Parameters.Add(new SqlParameter("@password", SqlDbType.VarChar, 20));
- //指定"@password"为输出参数
- password.Direction = ParameterDirection.Output;
- //执行
- sqlComm.ExecuteNonQuery();
- //得到输出参数的值,把赋值给name,注意,这里得到的是object类型的,要进行相应的类型轮换
- string passwrod = Convert.ToString(sqlComm.Parameters["@password"].Value);
- MessageBox.Show(passwrod);
- }
- }