SQL Server Stored Procedures and SQL Server Stored Procedures

Source: Internet
Author: User
Tags stored procedure example

SQL Server Stored Procedures and SQL Server Stored Procedures

Stored Procedures in Transact-SQL are very similar to methods in Java. They can be called repeatedly. After the stored procedure is executed once, you can cache the statements so that the statements in the cache are directly used for the next execution. This improves the performance of stored procedures.

Concept of Stored Procedure

Stored Procedure is a set of SQL statements for specific functions. Compiled and stored in the database. You can specify the name of the stored Procedure and provide parameters for execution.

Stored Procedures can contain logical control statements and data manipulation statements. They can accept parameters, output parameters, return one or more result sets, and return values.

Since the stored procedure is compiled on the database server and stored in the database at the time of creation, the stored procedure runs faster than a single SQL statement block. At the same time, because you only need to provide the stored procedure name and necessary parameter information during the call, it can also reduce network traffic and simple network burden to a certain extent.

 

1. Advantages of Stored Procedures

A. stored procedures allow standard component programming

After a stored procedure is created, it can be called and executed multiple times in the program without re-writing the SQL statement of the stored procedure. Database professionals can modify the stored procedure at any time, but it has no impact on the application source code, which greatly improves the program portability.

B. Fast execution of Stored Procedures

If an operation contains a large number of T-SQL statement codes that are executed multiple times, the stored procedure is much faster than the batch execution. Because the stored procedure is pre-compiled, when a stored procedure is run for the first time, the query optimizer analyzes and optimizes the stored procedure and provides the storage plan that is finally stored in the system table. The T-SQL Statement of batch processing needs to be pre-compiled and optimized every time, so the speed will be slower.

C. reduce network traffic through stored procedures

For the same database object operation, if the T-SQL statements involved in this operation are organized into a stored procedure, when the stored procedure is called on the client, only this call statement is passed in the network; otherwise, multiple SQL statements are passed. This reduces network traffic and network load.

D. stored procedures can be fully utilized as a security mechanism

The system administrator can restrict the permissions of a stored procedure to prevent unauthorized users from accessing data and ensure data security.

 

System stored procedures

A system stored procedure is a stored procedure created by the system. It is designed to conveniently query information from the system table or complete management tasks related to updating database tables or other system management tasks. The system stored procedures are mainly stored in the master database and stored procedures starting with "sp. Although these system stored procedures are in the master database, we can still call the system stored procedures in other databases. Some system stored procedures are automatically created in the current database when a new database is created.

Common system stored procedures include:

Exec sp_databases; -- view the database
Exec sp_tables; -- view the table
Exec sp_columns student; -- View Columns
Exec sp_helpIndex student; -- view the index
Exec sp_helpConstraint student; -- Constraint
Exec sp_stored_procedures;
Exec sp_helptext 'SP _ stored_procedures '; -- view the stored procedure creation and definition statements.
Exec sp_rename student, stuInfo; -- modify the names of tables, indexes, and columns.
Exec sp_renamedb myTempDB, myDB; -- change the Database Name
Exec sp_defaultdb 'master', 'mydb'; -- change the default database name
Exec sp_helpdb; -- Database Help, query database information
Exec sp_helpdb master;

System Stored Procedure example:
-- Rename a table
Exec sp_rename 'stu', 'stud ';
Select * from stud;
-- Rename a column
Exec sp_rename 'stud. name', 'sname', 'column ';
Exec sp_help 'stud ';
-- Rename an index
Exec sp_rename N 'student. idx_cid ', n'idx _ cid', n'index ';
Exec sp_help 'student ';

-- Query all stored procedures
Select * from sys. objects where type = 'P ';
Select * from sys. objects where type_desc like '% pro %' and name like 'SP % ';

 

User-Defined stored procedures

1. Create a syntax

Create proc | procedure pro_name
[{@ Parameter data type} [= default value] [output],
{@ Parameter data type} [= default value] [output],
....
]
As
SQL _statements

 

2. Create a stored procedure without Parameters

-- Create a stored procedure
If (exists (select * from sys. objects where name = 'proc _ get_student '))
Drop proc proc_get_student
Go
Create proc proc_get_student
As
Select * from student;

-- Call and execute stored procedures
Exec proc_get_student;

3. Modify the Stored Procedure

-- Modify the Stored Procedure
Alter proc proc_get_student
As
Select * from student;

4. Stored Procedure with Parameters

-- Stored procedure with Parameters
If (object_id ('proc _ find_stu ', 'P') is not null)
Drop proc proc_find_stu
Go
Create proc proc_find_stu (@ startId int, @ endId int)
As
Select * from student where id between @ startId and @ endId
Go

Exec proc_find_stu 2, 4;

5. Stored Procedures with wildcard Parameters

-- Stored procedure with wildcard Parameters
If (object_id ('proc _ findstudentbyname', 'P') is not null)
Drop proc proc_findStudentByName
Go
Create proc proc_findStudentByName (@ name varchar (20) = '% j %', @ nextName varchar (20) = '% ')
As
Select * from student where name like @ name and name like @ nextName;
Go

Exec proc_findStudentByName;
Exec proc_findStudentByName '% o %','t % ';

6. Stored Procedure with output parameters

If (object_id ('proc _ getStudentRecord ', 'P') is not null)
Drop proc proc_getStudentRecord
Go
Create proc proc_getStudentRecord (
@ Id int, -- default input parameter
@ Name varchar (20) out, -- output parameter
@ Age varchar (20) output -- Input and output Parameters
)
As
Select @ name = name, @ age = age from student where id = @ id and sex = @ age;
Go

--
Declare @ id int,
@ Name varchar (20 ),
@ Temp varchar (20 );
Set @ id = 7;
Set @ temp = 1;
Exec proc_getStudentRecord @ id, @ name out, @ temp output;
Select @ name, @ temp;
Print @ name + '#' + @ temp;
 

7. Non-Cache stored procedures

-- With recompile is not cached
If (object_id ('proc _ temp ', 'P') is not null)
Drop proc proc_temp
Go
Create proc proc_temp
With recompile
As
Select * from student;
Go

Exec proc_temp;

8. Encrypted storage process

-- ENCRYPTION WITH ENCRYPTION
If (object_id ('proc _ temp_encryption ', 'P') is not null)
Drop proc proc_temp_encryption
Go
Create proc proc_temp_encryption
With encryption
As
Select * from student;
Go

Exec proc_temp_encryption;
Exec sp_helptext 'proc _ temp ';
Exec sp_helptext 'proc _ temp_encryption ';

9. Stored Procedures with cursor Parameters

If (object_id ('proc _ cursor ', 'P') is not null)
Drop proc proc_cursor
Go
Create proc proc_cursor
@ Cur cursor varying output
As
Set @ cur = cursor forward_only static
Select id, name, age from student;
Open @ cur;
Go
-- Call
Declare @ exec_cur cursor;
Declare @ id int,
@ Name varchar (20 ),
@ Age int;
Exec proc_cursor @ cur = @ exec_cur output; -- call the Stored Procedure
Fetch next from @ exec_cur into @ id, @ name, @ age;
While (@ fetch_status = 0)
Begin
Fetch next from @ exec_cur into @ id, @ name, @ age;
Print 'id: '+ convert (varchar, @ id) +', name: '+ @ name +', age: '+ convert (char, @ age );
End
Close @ exec_cur;
Deallocate @ exec_cur; -- delete a cursor
 

10. Paging Stored Procedure

--- Stored procedure and row_number complete Paging
If (object_id ('Pro _ page', 'P') is not null)
Drop proc proc_cursor
Go
Create proc pro_page
@ StartIndex int,
@ EndIndex int
As
Select count (*) from product
;
Select * from (
Select row_number () over (order by pid) as rowId, * from product
) Temp
Where temp. rowId between @ startIndex and @ endIndex
Go
-- Drop proc pro_page
Exec pro_page 1, 4
--
-- Paging Stored Procedure
If (object_id ('Pro _ page', 'P') is not null)
Drop proc pro_stu
Go
Create procedure pro_stu (
@ PageIndex int,
@ PageSize int
)
As
Declare @ startRow int, @ endRow int
Set @ startRow = (@ pageIndex-1) * @ pageSize + 1
Set @ endRow = @ startRow + @ pageSize-1
Select * from (
Select *, row_number () over (order by id asc) as number from student
) T
Where t. number between @ startRow and @ endRow;

Exec pro_stu 2, 2;
 

Ø Raiserror

Raiserror returns the User-Defined error message. You can specify the Severity Level and set the system variable record errors.

Syntax:

Raiserror({msg_id | msg_str | @local_variable}
{, severity, state}
[,argument[,…n]]
[with option[,…n]]
)

# Msg_id: User-Defined error information specified in the sysmessages system table

# Msg_str: User-defined information. The maximum length of the information is 2047 characters.

# Severity: The severity level associated with the message. When msg_id is used to trigger a user-defined message created using sp_addmessage, the specified severity on raiserror overwrites the severity defined in sp_addmessage.

Any user can specify 0-18 direct severity levels. Only users frequently used by sysadmin fixed server roles or having the alter trace permission can specify a direct Severity Level. The with log option is required for security levels between and.

# State: any integer between 1 and 127. The default value of State is 1.

Raiserror ('is error', 16, 1 );
Select * from sys. messages;
-- Use the message defined in sysmessages
Raiserror (33003, 16, 1 );
Raiserror (33006, 16, 1 );

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.