C # Executes a stored procedure Code instance that demonstrates how to invoke and execute SQL Server's stored procedures in C #, an advanced application of a database that is relatively professional, but more efficient, and makes SQL more powerful, a simple example of a stored procedure invocation:
01using System;
02using System.Data;
03using System.Data.SqlClient;
04namespace executestorageprocess
259
Executestorageprocess public class
07 {
The public static void Main ()
09 {
Ten SqlConnection mysqlconnection =
One new SqlConnection (
"Server=localhost;database=northwind;uid=sa;pwd=sa"
13);
Mysqlconnection.open ();
15//Set CommandText property to execute statement
SqlCommand Mysqlcommand = Mysqlconnection.createcommand ();
Mysqlcommand.commandtext =
"EXECUTE addproduct @MyProductID OUTPUT, @MyProductName," +
"@MySupplierID, @MyCategoryID, @MyQuantityPerUnit," +
"@MyUnitPrice, @MyUnitsInStock, @MyUnitsOnOrder," +
"@MyReorderLevel, @MyDiscontinued";
22//Add parameters to the procedure call
MYSQLCOMMAND.PARAMETERS.ADD ("@MyProductID", SqlDbType.Int);
mysqlcommand.parameters["@MyProductID"]. Direction =
ParameterDirection.Output;
MYSQLCOMMAND.PARAMETERS.ADD (
"@MyProductName", SqlDbType.NVarChar, 40). Value = "Widget";
MYSQLCOMMAND.PARAMETERS.ADD (
"@MySupplierID", SqlDbType.Int). Value = 1;
MYSQLCOMMAND.PARAMETERS.ADD (
"@MyCategoryID", SqlDbType.Int). Value = 1;
MYSQLCOMMAND.PARAMETERS.ADD (
"@MyQuantityPerUnit", SqlDbType.NVarChar, 20). Value = "1 per box";
MYSQLCOMMAND.PARAMETERS.ADD (
"@MyUnitPrice", Sqldbtype.money). Value = 5.99;
MYSQLCOMMAND.PARAMETERS.ADD (
Panax Notoginseng "@MyUnitsInStock", Sqldbtype.smallint). Value = 10;
MYSQLCOMMAND.PARAMETERS.ADD (
"@MyUnitsOnOrder", Sqldbtype.smallint). Value = 5;
MYSQLCOMMAND.PARAMETERS.ADD (
"@MyReorderLevel", Sqldbtype.smallint). Value = 5;
MYSQLCOMMAND.PARAMETERS.ADD (
"@MyDiscontinued", Sqldbtype.bit). Value = 1;
44//Execute command
Mysqlcommand.executenonquery ();
46//Read the value of the output parameter
Console.WriteLine ("New ProductID =" +
mysqlcommand.parameters["@MyProductID"]. Value);
Mysqlconnection.close ();
50}
51}
32;
This code does not include the database's stored procedure entities, and you can manually create one yourself.
Note : Please pay attention to the triple programming Tutorials section for more wonderful articles .