SQL stored procedure (ASP. NET)

Source: Internet
Author: User
Tags sql server query

Using Stored Procedures in ASP. Net projects can first improve database security, and secondly improve the speed of running SQL code, which is generally essential for large projects. Visual Studio. net provides powerful support for SQL stored procedures. You can use visual studio.net to create a stored procedure, or directly run it in the SQL Server Query analyzer, it can also be created through the Enterprise Manager for ease of use. We have always mistakenly believed that SQL stored procedures are a relatively "advanced" technology. In fact, there is no major problem in mastering general syntax, and we are in the use of storage tutorials is also mainly added to delete the operation, learn to use the general T-SQL is very easy to get started.
Let's take a look at how to create a stored procedure in SQL server. We can use SQL command statements to create a stored procedure, or use the Enterprise Manager in SQL server to create a stored procedure, but in fact, they can't do without writing their own statements. Of course, we don't need to change the system stored procedures (stored procedures include system stored procedures, local stored procedures, temporary stored procedures, and remote stored procedures, extended Stored Procedures), while local stored procedures are stored in our own stored procedures, which are also called user stored procedures.

When creating a stored procedure, you must determine the three components of the stored procedure.
All input parameters and output parameters passed to the caller
The executed database-specific operation statements include statements that call other stored procedures.
The status value returned to the caller to indicate whether the call is successful or failed.
1. Create a stored procedure
1. Use the Enterprise Manager to create a stored procedure;
Open the Enterprise Manager and find the database for which you want to create the stored procedure.

We can see that there is a stored procedure project in the database, and we need to use it. Select the Stored Procedure project, we can see that there are a lot of stored procedures in the database itself, but these are included in the database itself, we can see that its type is system, if we create a stored procedure, the type is user.

On the left side of the control tree, right-click the stored procedure and choose create stored procedure from the shortcut menu"

Select this option and a new window will appear. This window is used to write the stored procedure.

In actual application, the stored procedure we created is not as complex as we imagined, and none of the above parameters are used, however, before using the query analyzer to create a stored procedure, we will use the following statement to check whether a stored procedure with the same name already exists in the database. If so, delete it first.

If exists (select name from sysobjects where name = 'stored procedure name' and type = 'P ')
Drop procedure stored procedure name
Go

Here, we know how to delete a stored procedure, that is, using the drop procedure keyword + stored procedure name.

Let's first list several common stored procedures:

A. stored procedures without Parameters

Create procedure com_select
As
Select * from Company
GO

B. Stored Procedures with Parameters

Create procedure admin_select
@ Adminusername char (50 ),
@ Adminpassword char (50)
As
Select * from superadmin where
[Admin_Name] = @ adminusername and [Admin_Password] = @ adminpassword
GO

C. stored procedures in which OUTPUT reserved words have returned values are used
Create procedure salequa
@ Stor_id char (4 ),
@ Sum smallint output
As
Select
Ord_num, ord_date,
Payterms, title_id,
Qty
From sales
Where stor_id = @ stor_id
Select @ sum = sum (qty)
From sales
Where stor_id = @ stor_id
Go

The above several stored procedures are basic stored procedures. At the same time, we can see that the annotations in the stored procedures are in the form of/* Annotations.

Let's talk about the usage of stored procedures in. net next time.
Ii. Storage Process usage

1. Execute in SQL
Run the EXECUTE Command to EXECUTE the created stored procedure. The syntax is as follows:
[EXECUTE]
{[@ Return_statur =]
{Procedure_name [; number] | @ procedure_name_var}
[[@ Parameter =] {value | @ variable [OUTPUT] | [DEFAULT] [,… N]
[With recompile]
The meanings of parameters are as follows:
@ Return_status
Is an optional integer variable used to store the value returned by the stored procedure to the caller.
@ Procedure_name_var
Is a variable name used to represent the name of the stored procedure
The meanings of other parameter data and reserved words are the same as those described in create procedure.

For example, we have a stored procedure named student_list_info to execute. In the query analyzer, you only need to write
Execute student_list_info
Go
You can.
If a Stored Procedure contains a stored procedure with a returned value, you must specify the parameter value. See the following example.
This example is taken from programmer's guide.
Create procedure salequa @ stor_id char 4, @ sum smallint output
As
Select ord_num, ord_date, payterms, title_id, qty
From sales
Where stor_id = @ stor_id
Select @ sum = sum qty
From sales
Where stor_id = @ stor_id
Go

To execute this stored procedure, specify the parameter @ sort_id and @ sum.
Declare @ totalqua smallint
Execute salequa '000000', @ totalqua output
If @ totalqua <= 50
Select 'sales information' = 'sale Level 3 sales volume '+ rtrim cast @ totalqua as varchar 20
If @ totalqua> 50 and @ totalqua <= 100
Select 'sales information' = 'sale Level 2 sales volume '+ rtrim cast @ totalqua as varchar 20
If @ totalqua> 100
Select 'sales information' = 'sales grade is 1 Sales Volume '+ rtrim cast @ totalqua as varchar 20
The running result is
Ord_num ord_date payterms title_id qty
-------------------------------------------------------------------------
N914008 1994-09-14 00:00:00. 000 Net 30 PS2091 20
N914014 1994-09-14 00:00:00. 000 Net 30 MC3021 25
P3087a 1993-05-29 00:00:00. 000 Net 60 PS1372 20
P3087a 1993-05-29 00:00:00. 000 Net 60 PS2106 25
P3087a 1993-05-29 00:00:00. 000 Net 60 PS3333 15
P3087a 1993-05-29 00:00:00. 000 Net 60 ps77
6 row s affected
Sales Information
-----------------------------------------
The sales level is 1. The sales volume is 130.

2. Use stored procedures in ASP. NET
In ASP. net (c # is used here). First, check whether System is referenced on the page. data. sqlclient; of course, database connection is essential. We know that the steps for calling data in Asp. Net are as follows:

Create a database connection object (SqlConnection) → Open the database to be operated using the Open () method → create a SqlCommand or SqlDataAdapter object → ExecuteNonQuery () for SQL commands or stored procedures () method or ExecuteReader () method to perform data operations → read or input data to the database → Close the connection using the Close () method.

We can see that before using stored procedures, we should use the SqlCommand object or SqlDataAdapter object to fill the DataSet or co-existence in the use of stored procedures. however, the method used is not very different from the method used to directly execute SQL statements in Net. We can use examples to illustrate how to call a stored procedure.

(1) Use a SqlCommand object

 


String spid = Request. QueryString ["supplyid"]. Trim ();
SqlConnection conndb = new SqlConnection (System. Configuration. ConfigurationSettings. deleettings ["conn"]);
Conndb. Open ();
SqlCommand strselect = new SqlCommand ("supplyinfo_select_supplyid", conndb );
Strselect. CommandType = CommandType. StoredProcedure;
Strselect. Parameters. Add ("@ supply_ID", spid );
SqlDataReader reader = strselect. ExecuteReader ();
If (reader. Read ())
{
LblId. Text = reader ["Supply_Id"]. ToString (). Trim ();
LblTitle. Text = reader ["Supply_Subject"]. ToString (). Trim ();
LblBigclass. Text = reader ["Supply_CatID"]. ToString (). Trim ();
LblDesc. Text = reader ["Supply_Details"]. ToString (). Trim ();
LblPurType. Text = reader ["Supply_PurchaseType"]. ToString (). Trim ();
If (int. Parse (reader ["Supply_Ischecked"]. ToString (). Trim () = 1)
{
LblIschk. Text = "approved ";
}
Else
{
LblIschk. Text = "not approved ";
}
If (int. Parse (reader ["Supply_Isrcmd"]. ToString (). Trim () = 1)
{
LblIsrcmd. Text = "recommended ";
}
Else
{
LblIsrcmd. Text = "not set as Recommendation ";
}
Switch (reader ["Supply_Reader_Level"]. ToString (). Trim ())
{
Case "0 ":
LblLevel. Text = "setting everyone can see this information ";
Break;
Case "1 ":
LblLevel. Text = "set this information for registered members ";
Break;
Case "2 ":
LblLevel. Text = "set VIP members to see this information ";
Break;
}
}

 

From the above we can see that the key statement for calling a stored procedure using the SqlCommand object is:
SqlCommand strselect = new SqlCommand ("supplyinfo_select_supplyid", conndb );
Strselect. CommandType = CommandType. StoredProcedure;
Strselect. Parameters. Add ("@ supply_ID", spid );
Simple Explanation: declare a SqlCommand object and call the Stored Procedure supplyinfo_select_supplyid through SqlCommand,
At the same time, it contains an input parameter @ supply_id whose value is the variable spid. At the same time, it queries data related to the data through the ExecuteReader () method and displays the data through the label control.

(2) Use the SqlDataAdapter object

Program code:

Private void buycatalog ()
{
SqlConnection conndb = new SqlConnection (System. Configuration. ConfigurationSettings. deleettings ["conn"]);
Conndb. Open ();
SqlDataAdapter strselect = new SqlDataAdapter ("productclass", conndb );

Strselect. SelectCommand. CommandType = CommandType. StoredProcedure;

DataSet ds = new DataSet ();

Strselect. Fill (ds );

DlstBuycatalog. DataSource = ds;

DlstBuycatalog. DataKeyField = "PdtCat_ID ";

DlstBuycatalog. DataBind ();

Conndb. Close ();
}

The above method is to use the SqlDataAdapter to call the SQL stored procedure productclass, fill the data in ds through DataSet, and specify that the data source of the DataList control DlstBuycatalog is ds, and the primary key is PdtCat_Id, then re-bind the Datalist control. in this method, we can see that the key to calling the stored procedure with SqlDataAdapter is:
SqlDataAdapter strselect = new SqlDataAdapter ("productclass", conndb );
Strselect. SelectCommand. CommandType = CommandType. StoredProcedure;
What should we do when there are parameters in the stored procedure? In fact, this is similar to SqlCommand. We only need to add one more sentence.
Strselect. SelectCommand. Parameter. Add ("@ pdt_name", txtpdtname. Text ());
Here, @ pdt_name is the parameter variable name declared in the stored procedure, while txtpdtname. text () is the value assigned to the variable @ pdt_name in. net. Take a closer look at the following stored procedure:
From the above, we can know that the most critical object in the stored procedure is the Command object. This object can be executed through the ExecuteReader () method, and a single value query can be returned, you can also use the ExecuteScalar () method to perform relevant data statistics, or use the ExecuteNonQuery () method to update data, add, delete, modify, and execute operations. When you execute these SQL operations, it is often used in combination with the related control DataGrid, DataList, and Repeat controls.

(3) Examples of common stored procedures
The following are some of the stored procedures used in a recent project. They may not be well written due to their limited level, however, most of the results I want are implemented. These stored procedures can be executed normally and sent to you (please forgive me for keeping the database confidential). I hope it will be useful to you, I also hope to correct the error. Thank you.
(1) select all records

Create procedure sellinfo_select
As
Select * from sellinfo
GO

(2) Delete the specified ID record

Create procedure sellinfo_delete
@ Sell_id bigint
As
Delete from [sellinfo]
Where
Sell_id = @ sell_id
GO
(3) update the corresponding record

Program code:

Create procedure prosmallclass_update_id
@ Smallid int,
@ Smallname char (50)
As
Update [ProductCats]
Set
PdtCat_Name = @ smallname
Where
PdtCat_id = @ smallid
GO
(4) Verify Login

 

CREATE procedure user_login
@ User_name varchar (50 ),
@ User_password varchar (50)
As
Select * from usercompany where [User_Name] = @ User_Name and [User_Pwd] = @ User_Password
If @ rowcount> 0
Begin
Update [users] set

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.