什么是“存储过程”,它们是如何工作的?

存储过程是由什么组成的(每个东西都必须是存储过程)?


当前回答

对于简单的,

存储过程是存储程序,存储在数据库中的程序或函数。

每个存储的程序都包含一个由SQL语句组成的主体。该语句可以是由几个用分号(;)分隔的语句组成的复合语句。

CREATE PROCEDURE dorepeat(p1 INT)
BEGIN
  SET @x = 0;
  REPEAT SET @x = @x + 1; UNTIL @x > p1 END REPEAT;
END;

其他回答

在DBMS中,存储过程是一组具有指定名称的SQL语句,这些SQL语句以编译后的形式存储在数据库中,这样就可以由许多程序共享。

存储过程的使用在

提供对数据的受控访问(最终用户只能输入或更改数据,但不能编写过程) 确保数据完整性(数据将以一致的方式输入)和 提高工作效率(存储过程的语句只需编写一次)

create procedure <owner>.<procedure name><param> <datatype>
As
    <body>

存储过程是将数据访问集中在一点上的SQL语句组。适用于在一个镜头中执行多个操作。

存储过程不过是编译成单个执行计划的一组SQL语句。

创建一次,调用n次 减少网络流量

示例:创建存储过程

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE GetEmployee
      @EmployeeID int = 0
AS
BEGIN
      SET NOCOUNT ON;

      SELECT FirstName, LastName, BirthDate, City, Country
      FROM Employees 
      WHERE EmployeeID = @EmployeeID
END
GO

更改或修改存储过程:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE GetEmployee
      @EmployeeID int = 0
AS
BEGIN
    SET NOCOUNT ON;

    SELECT FirstName, LastName, BirthDate, City, Country
    FROM Employees 
    WHERE EmployeeID = @EmployeeID
END
GO

删除存储过程:

DROP PROCEDURE GetEmployee

在存储过程中,语句只被写入一次,从而减少了客户端和服务器之间的网络流量。 我们也可以避免Sql注入攻击。

Incase if you are using a third party program in your application for processing payments, here database should only expose the information it needed and activity that this third party has been authorized, by this we can achieve data confidentiality by setting permissions using Stored Procedures. The updation of table should only done to the table it is targeting but it shouldn't update any other table, by which we can achieve data integrity using transaction processing and error handling. If you want to return one or more items with a data type then it is better to use an output parameter. In Stored Procedures, we use an output parameter for anything that needs to be returned. If you want to return only one item with only an integer data type then better use a return value. Actually the return value is only to inform success or failure of the Stored Procedure.

一般来说,存储过程是一个“SQL函数”。他们有:

-- a name
CREATE PROCEDURE spGetPerson
-- parameters
CREATE PROCEDURE spGetPerson(@PersonID int)
-- a body
CREATE PROCEDURE spGetPerson(@PersonID int)
AS
SELECT FirstName, LastName ....
FROM People
WHERE PersonID = @PersonID

这是一个以T-SQL为重点的示例。存储过程可以执行大多数SQL语句,返回标量值和基于表的值,并且被认为更安全,因为它们可以防止SQL注入攻击。