① Call a stored procedure without parameters in Asp.net
Create proc select_tid
Select TID from my_test where tname = 'aillo'
Protected void page_load (Object sender, eventargs E)
{
// Stored procedure without parameters ①
String constr = "database = test ";
Contodatabase CTD = new contodatabase (constr );
Sqlconnection con = CTD. getcon ();
// Contodatabase Is your own defined class, getcon () is the custom method to connect to the database.
Sqlcommand cmd = new sqlcommand ("select_tid", con );
Cmd. commandtype = commandtype. storedprocedure;
String result = "";
Try
{
Con. open ();
Sqldatareader myreader = cmd. executereader ();
While (myreader. Read ())
{
If (myreader [0]. tostring ()! = "")
{
Response. Write (myreader [0]. tostring ());
}
}
}
Catch (exception ex)
{
Result = ex. tostring ();
}
Finally
{
Con. Close ();
}
}
② Call the stored procedure with Parameters
Create procedure select_by_age
@ Min_age int,
@ Max_age int
As
Select CID as 'number', cname as 'name', age as 'age', sex as 'gender' from MERs where age >=@ min_age and age <= @ max_age
Protected void page_load (Object sender, eventargs E)
{
// Stored procedure with Parameters
String constr = "database = test ";
Contodatabase CTD = new contodatabase (constr );
Sqlconnection con = CTD. getcon ();
Sqldataadapter da = new sqldataadapter ("select_by_age", con );
Da. selectcommand. commandtype = commandtype. storedprocedure;
Sqlparameter par0, par1;
Par0 = new sqlparameter ("@ min_age", 5 );
Par1 = new sqlparameter ("@ max_age", 18 );
Da. selectcommand. Parameters. Add (par0 );
Da. selectcommand. Parameters. Add (par1 );
Dataset DS = new dataset ();
String result = "";
Try
{
Con. open ();
Da. Fill (DS );
Gridview1.datasource = Ds;
Gridview1.databind ();
}
Catch (exception ex)
{
Result = ex. tostring ();
}
Finally
{
Con. Close ();
}
}
③ Call the stored procedure with judgment
Create procedure select_if
@ Age int
As
If @ age = 5
Begin
Select * from MERs where age = @ age
End
Else
Begin
Select * from MERs where age <> 5
End
Protected void page_load (Object sender, eventargs E)
{
// The stored procedure with judgment. The passed parameters are used to determine which SQL statement to execute.
String constr = "database = test ";
Contodatabase CTD = new contodatabase (constr );
Sqlconnection con = CTD. getcon ();
Sqldataadapter da = new sqldataadapter ("select_if", con );
Da. selectcommand. commandtype = commandtype. storedprocedure;
Sqlparameter par0;
Par0 = new sqlparameter ("@ age", 11 );
Da. selectcommand. Parameters. Add (par0 );
Dataset DS = new dataset ();
String result = "";
Try
{
Con. open ();
Da. Fill (DS );
Gridview1.datasource = Ds;
Gridview1.databind ();
}
Catch (exception ex)
{
Result = ex. tostring ();
}
Finally
{
Con. Close ();
}
}