search
HomeDatabaseSQLA brief discussion of database stored procedures

A brief discussion of database stored procedures

Jun 14, 2019 am 11:25 AM
stored proceduredatabase

A brief discussion of database stored procedures

What is a stored procedure

If you have been exposed to other programming languages, then it will be easier to understand. Stored procedures are just like methods. .

It turns out that it is a method, so it has a similar method name, variables to be passed by the method and return results, so the stored procedure has a stored procedure name, stored procedure parameters and return value.

Advantages of stored procedures:

  • The ability of stored procedures greatly enhances the functionality and flexibility of the SQL language.
  • Can ensure the security and integrity of data.
  • Through stored procedures, users without permissions can indirectly access the database under control, thereby ensuring data security.
  • Through stored procedures, related actions can occur together, thereby maintaining the integrity of the database.
  • Before running the stored procedure, the database has analyzed its grammar and syntax and provided an optimized execution plan. This compiled process can greatly improve the performance of SQL statements.
  • Can reduce network traffic.
  • Put the computing program that embodies the enterprise rules into the database server for centralized control.

Stored procedures can be divided into system stored procedures, extended stored procedures and user-defined stored procedures

System stored procedures

We Let's first take a look at the system stored procedures. The system stored procedures are defined by the system and are mainly stored in the MASTER database. The names start with "SP" or "XP". Although these system stored procedures are in the MASTER database, we can still call system stored procedures in other databases. There are some system stored procedures that are automatically created in the current database when a new database is created.

Commonly used system stored procedures are:

exec sp_databases; --View database
  • exec sp_tables; --View table
  • exec sp_columns student ;--View columns
  • exec sp_helpIndex student;--View index
  • exec sp_helpConstraint student;--Constraints
  • exec sp_helptext 'sp_stored_procedures';--View stored procedure creation Defined statement
  • exec sp_stored_procedures;
  • exec sp_rename student, stuInfo;--change the table name
  • exec sp_renamedb myTempDB, myDB;--change the database name
  • exec sp_defaultdb 'master', 'myDB';--Change the default database for login name
  • exec sp_helpdb;--Database help, query database information
  • exec sp_helpdb master;
  • exec sp_attach_db --Attach database
  • exec sp_detach_db --Detach database
  • Stored procedure syntax:

Before creating a stored procedure, let’s talk about it first Let’s talk about the naming of stored procedures. I saw that several articles about stored procedures like to add a prefix when creating a stored procedure. It is important to develop the habit of adding a prefix before the name of a stored procedure. Although this is only a small thing, But often small details determine big success or failure. I saw that some people like to add prefixes like this, such as proc_name. Also see this prefix usp_name. The former proc is the abbreviation of procedure, and the latter sup means user procedure. I prefer the first method, so all the stored procedure names below will be written in the first method. As for the writing of the name, the camel nomenclature is used.

The syntax for creating a stored procedure is as follows:

CREATE PROC[EDURE] 存储过程名 

@参数1 [数据类型]=[默认值] [OUTPUT] 

@参数2 [数据类型]=[默认值] [OUTPUT]

AS 

SQL语句

EXEC 过程名[参数]

Use a stored procedure instance:

1. Without parameters

create procedure proc_select_officeinfo--(存储过程名)as select Id,Name from Office_Info--(sql语句)

exec proc_select_officeinfo--(调用存储过程)

2. With input parameters

create procedure procedure_proc_GetoffinfoById ----  Name  dbo.Office_Info  Id=@Id----(存储过程名称之后,空格加上参数,多个参数中间以逗号分隔)

注:参数赋值是,第一个参数可以不写参数名称,后面传入参数,需要明确传入的是哪个参数名称

3. With input and output parameters

create procedure proc_office_info--( Stored procedure name)
@Id int,@Name varchar(20) output--(parameter name parameter type) Outgoing parameters should be added with output

as
begin
select @Name=Name from dbo.Office_Info where Id=@Id --(sql statement)
end

declare @houseName varchar(20) --Declare a variable and get the value passed by the stored procedure

exec proc_office_info- -(stored procedure name)

4,@houseName output--(It is said that the parameter needs to add output. If you use @variable = OUTPUT here, an error will be reported, so change the writing method)

select @houseName-- (Display value)

4. With return value

create procedure proc_office_info--(存储过程名)
@Id int--(参数名 参数类型)as beginif(select Name from dbo.Office_Info where Id=@Id)=null --(sql语句)
beginreturn -1endelsebeginreturn 1end
end

declare @house varchar(20) --声明一个变量,获取存储过程传出来的值
exec @house=proc_office_info 2 --(调用存储过程,用变量接收返回值)--注:带返回值的存储过程只能为int类型的返回值
print @house
For more technical articles related to SQL, please visit

SQL tutorial column to learn!

The above is the detailed content of A brief discussion of database stored procedures. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
SQL: A Beginner-Friendly Approach to Data Management?SQL: A Beginner-Friendly Approach to Data Management?Apr 19, 2025 am 12:12 AM

SQL is suitable for beginners because it is simple in syntax, powerful in function, and widely used in database systems. 1.SQL is used to manage relational databases and organize data through tables. 2. Basic operations include creating, inserting, querying, updating and deleting data. 3. Advanced usage such as JOIN, subquery and window functions enhance data analysis capabilities. 4. Common errors include syntax, logic and performance issues, which can be solved through inspection and optimization. 5. Performance optimization suggestions include using indexes, avoiding SELECT*, using EXPLAIN to analyze queries, normalizing databases, and improving code readability.

SQL in Action: Real-World Examples and Use CasesSQL in Action: Real-World Examples and Use CasesApr 18, 2025 am 12:13 AM

In practical applications, SQL is mainly used for data query and analysis, data integration and reporting, data cleaning and preprocessing, advanced usage and optimization, as well as handling complex queries and avoiding common errors. 1) Data query and analysis can be used to find the most sales product; 2) Data integration and reporting generate customer purchase reports through JOIN operations; 3) Data cleaning and preprocessing can delete abnormal age records; 4) Advanced usage and optimization include using window functions and creating indexes; 5) CTE and JOIN can be used to handle complex queries to avoid common errors such as SQL injection.

SQL and MySQL: Understanding the Core DifferencesSQL and MySQL: Understanding the Core DifferencesApr 17, 2025 am 12:03 AM

SQL is a standard language for managing relational databases, while MySQL is a specific database management system. SQL provides a unified syntax and is suitable for a variety of databases; MySQL is lightweight and open source, with stable performance but has bottlenecks in big data processing.

SQL: The Learning Curve for BeginnersSQL: The Learning Curve for BeginnersApr 16, 2025 am 12:11 AM

The SQL learning curve is steep, but it can be mastered through practice and understanding the core concepts. 1. Basic operations include SELECT, INSERT, UPDATE, DELETE. 2. Query execution is divided into three steps: analysis, optimization and execution. 3. Basic usage is such as querying employee information, and advanced usage is such as using JOIN connection table. 4. Common errors include not using alias and SQL injection, and parameterized query is required to prevent it. 5. Performance optimization is achieved by selecting necessary columns and maintaining code readability.

SQL: The Commands, MySQL: The EngineSQL: The Commands, MySQL: The EngineApr 15, 2025 am 12:04 AM

SQL commands are divided into five categories in MySQL: DQL, DDL, DML, DCL and TCL, and are used to define, operate and control database data. MySQL processes SQL commands through lexical analysis, syntax analysis, optimization and execution, and uses index and query optimizers to improve performance. Examples of usage include SELECT for data queries and JOIN for multi-table operations. Common errors include syntax, logic, and performance issues, and optimization strategies include using indexes, optimizing queries, and choosing the right storage engine.

SQL for Data Analysis: Advanced Techniques for Business IntelligenceSQL for Data Analysis: Advanced Techniques for Business IntelligenceApr 14, 2025 am 12:02 AM

Advanced query skills in SQL include subqueries, window functions, CTEs and complex JOINs, which can handle complex data analysis requirements. 1) Subquery is used to find the employees with the highest salary in each department. 2) Window functions and CTE are used to analyze employee salary growth trends. 3) Performance optimization strategies include index optimization, query rewriting and using partition tables.

MySQL: A Specific Implementation of SQLMySQL: A Specific Implementation of SQLApr 13, 2025 am 12:02 AM

MySQL is an open source relational database management system that provides standard SQL functions and extensions. 1) MySQL supports standard SQL operations such as CREATE, INSERT, UPDATE, DELETE, and extends the LIMIT clause. 2) It uses storage engines such as InnoDB and MyISAM, which are suitable for different scenarios. 3) Users can efficiently use MySQL through advanced functions such as creating tables, inserting data, and using stored procedures.

SQL: Making Data Management Accessible to AllSQL: Making Data Management Accessible to AllApr 12, 2025 am 12:14 AM

SQLmakesdatamanagementaccessibletoallbyprovidingasimpleyetpowerfultoolsetforqueryingandmanagingdatabases.1)Itworkswithrelationaldatabases,allowinguserstospecifywhattheywanttodowiththedata.2)SQL'sstrengthliesinfiltering,sorting,andjoiningdataacrosstab

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.