C # Call the stored procedure with output parameters,
Write a stored procedure in SQL server:
- Create procedure ProGetPWD
- @ Username varchar (20 ),
- @ Password varchar (20) OUTPUT
- AS
- BEGIN
- SELECT @ password = password
- FROM Users
- WHERE username = @ username
- END
--------------------------
The following describes how to call a stored procedure in. 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 ())
- {
- // Set the name of the stored procedure to be called
- SqlComm. CommandText = "GetPWD ";
- // Specify the name of the stored procedure passed to the database by the SqlCommand object instead of the SQL statement.
- SqlComm. CommandType = CommandType. StoredProcedure;
- SqlParameter username = sqlComm. Parameters. Add (new SqlParameter ("@ username", SqlDbType. VarChar, 20 ));
- // Specify "@ username" as the input parameter
- Username. Direction = ParameterDirection. Input;
- // Assign a value to the "@ username" parameter
- Username. Value = this.txt _ username. Text;
- SqlParameter password = sqlComm. Parameters. Add (new SqlParameter ("@ password", SqlDbType. VarChar, 20 ));
- // Specify "@ password" as the output parameter
- Password. Direction = ParameterDirection. Output;
- // Execute
- SqlComm. ExecuteNonQuery ();
- // Obtain the value of the output parameter and assign the value to the name. Note that the value is of the object type, and the type rotation is required.
- String passwrod = Convert. ToString (sqlComm. Parameters ["@ password"]. Value );
- MessageBox. Show (passwrod );
- }
- }