存储过程中定义sql语句

Stored procedures (SPs) are one more powerful database object we have at our disposal. They can help us handle many tasks and improve performance and security. Today, we’ll take a look at simple SPs and show, on examples, how to use them.

存储过程(SP)是我们可以使用的功能更强大的数据库对象。 它们可以帮助我们处理许多任务,并提高性能和安全性。 今天,我们将看一下简单的SP,并在示例中展示如何使用它们。

该模型 (The Model)

As always, at the start of the article, we’ll remind ourselves of the data model we’re using.

与往常一样,在本文开头,我们将使自己想起正在使用的数据模型。

In this article, we’ll create simple stored procedures that will use a single table, and that will be the customer table.

在本文中,我们将创建简单的存储过程,该存储过程将使用一个表,即customer表。

什么是存储过程 (What Are Stored Procedures)

Stored procedures (SPs) in SQL Server are just like procedures/routines in other DBMSs or programming languages. Each procedure has one or more statements. In our case, these are SQL statements. So, you can write a procedure that will – insert new data, update or delete existing, retrieve data using the SELECT statement. And even better, you can combine more (different statements) in the stored procedures. Also, inside the procedure, you can call another SP, function, use the IF statement, etc. Therefore, it’s pretty obvious SP can do much more than a single select query.

SQL Server中的存储过程(SP)与其他DBMS或编程语言中的过程/例程相同。 每个过程都有一个或多个语句。 在我们的例子中,这些是SQL语句。 因此,您可以编写一个过程来–插入新数据,更新或删除现有数据,使用SELECT语句检索数据。 甚至更好的是,您可以在存储过程中组合更多(不同的语句)。 另外,在该过程中,您可以调用另一个SP,函数,使用IF语句等。因此,很明显,SP可以完成的功能比单个选择查询还多。

The main idea is to write down the procedure performing all the operations we want, and later, when needed, call this procedure using parameters. Therefore, an SP for the end-user would be like a black box, receiving input and returning the output.

主要思想是写下执行所需的所有操作的过程,然后在需要时使用参数调用该过程。 因此,最终用户的SP就像黑匣子一样,接收输入并返回输出。

存储过程–简单示例 (Stored Procedures – Simple Example)

Let’s now take a look at a few simple SPs. For the first example, we’ll create an SP returning all values from the customer table. To do that, we’ll use the following code:

现在让我们看一些简单的SP。 对于第一个示例,我们将创建一个返回客户表中所有值的SP。 为此,我们将使用以下代码:

DROP PROCEDURE IF EXISTS p_customer_all;
GO
CREATE PROCEDURE p_customer_all
-- procedure returns all rows from the customer table
AS BEGINSELECT *FROM customer;
END;

I want to emphasize a couple of things here:

我想在这里强调两点:

  • We’ve used the DROP PROCEDURE IF EXISTS p_customer_all; statement in the first line. This is nice practice, especially when you’re creating scripts you want to work always, no matter the state of the database. The command DROP PROCEDURE p_customer_all; would delete the procedure with the given name. Still, if the procedure wasn’t already created in the database, this would result in an error. Therefore, adding IF EXISTS prevents this from happening. This row generally says – I will delete this procedure if it’s on the server, and if it is not present, OK, do nothing 我们已经使用了DROP PROCEDURE IF EXISTS p_customer_all;。 第一行中的语句。 这是一个好习惯,特别是在创建脚本时,无论数据库处于何种状态,您都希望始终工作。 命令DROP PROCEDURE p_customer_all; 将删除具有给定名称的过程。 但是,如果尚未在数据库中创建该过程,则会导致错误。 因此,添加IF EXISTS可以防止这种情况的发生。 该行通常说–如果该步骤在服务器上,并且如果不存在,则将其删除,确定,什么也不做
  • The word GO is inserted between two SQL statements in situations like this one 在这种情况下,在两个SQL语句之间插入GO这个词
  • The name of our procedure is p_customer_all. The reason for that is as follows – “p” is for the procedure, followed by the table name (customer) and the action we’ll use this procedure for (return all) 我们的过程的名称为p_customer_all。 原因如下:“ p”代表过程,后跟表名(客户)以及我们将使用此过程进行的操作(全部返回)
  • The body of the procedure is just a simple select statement returning all rows from this table 该过程的主体只是一个简单的select语句,返回该表中的所有行

After the procedure is created, you can see it in the Object Explorer, under Programmability -> Stored Procedures.

创建过程后,您可以在对象资源管理器的“可编程性”->“存储过程”下看到它。

Let’s now call/execute our SP.

现在让我们调用/执行我们的SP。

To do this, we’ll use the syntax: EXEC procedure_name <parameters if any>;. So, our statement is:

为此,我们将使用以下语法:EXEC procedure_name <parameters if any>;。 因此,我们的声明是:

EXEC p_customer_all;

The result is shown in the picture below:

结果如下图所示:

As you can see, this procedure is pretty simple, and it did exactly the same job, the simple select would do. While this doesn’t seem to have benefits, actually, it does. Still, these benefits become even more visible on more complex procedures. We’ll talk about the advantages of using SPs in a minute.

如您所见,此过程非常简单,它执行的操作完全相同,简单的选择就可以完成。 尽管这似乎没有好处,但实际上确实有好处。 但是,这些好处在更复杂的过程中变得更加明显。 我们将在稍后讨论使用SP的优势。

存储过程–更复杂的示例 (Stored Procedures – More Complex Examples)

The previous example was pretty simple, but still nicely shows what SPs can do. Besides that, we can easily create SPs to get only one row, insert new or delete/updated existing row. We’ll show 3 examples – retrieving row by id, inserting new row & deleting an existing row. We’ll use the same naming convention rule, we’ve used in the previous example (p_table_name_action_name).

前面的示例非常简单,但是仍然很好地显示了SP可以执行的操作。 除此之外,我们可以轻松创建SP来仅获得一行,插入新行或删除/更新现有行。 我们将显示3个示例-按ID检索行,插入新行和删除现有行。 我们将使用在上一个示例中使用的相同命名约定规则(p_table_name_action_name)。

For the procedure that will return only one row based on the id, the code is:

对于仅返回基于id的一行过程,代码为:

DROP PROCEDURE IF EXISTS p_customer;
GO
CREATE PROCEDURE p_customer (@id INT)
-- procedure returns the entire row for the given id
AS BEGINSELECT *FROM customerWHERE id = @id;
END;

The new moment here is that we pass the parameter to the procedure. We can pass one or more parameters. We’ll list them all after the procedure name in the CREATE PROCEDURE line (CREATE PROCEDURE p_customer (@id INT)).

这里的新时刻是我们将参数传递给过程。 我们可以传递一个或多个参数。 我们将在CREATE PROCEDURE行(CREATE PROCEDURE p_customer(@id INT))中的过程名称之后列出所有它们。

Now we’re ready to execute our second procedure:

现在我们准备执行第二步:

EXEC p_customer 4;

The result is, as expected, all details for the customer with id = 4. Please notice that we’ve listed parameter(s) without “(“ and “)” after the procedure name in the EXEC line.

正如预期的那样,结果是id = 4的客户的所有详细信息。请注意,我们在EXEC行中的过程名称后面列出了不含“(”和“)”的参数。

Let’s now create a procedure that will insert a new customer in the table.

现在,让我们创建一个将在表中插入新客户的过程。

DROP PROCEDURE IF EXISTS p_customer_insert;
GO
CREATE PROCEDURE p_customer_insert (@customer_name VARCHAR(255), @city_id INT, @customer_address VARCHAR(255), @next_call_date DATE)
-- procedure inserts a new customer
AS BEGININSERT INTO customer (customer_name, city_id, customer_address, next_call_date, ts_inserted)VALUES (@customer_name, @city_id, @customer_address, @next_call_date, SYSDATETIME());
END;

The important things to notice here are:

这里要注意的重要事项是:

  • We’ve used more than 1 parameter in this procedure 在此过程中,我们使用了多个参数
  • For the value ts_inserted, we’ve used the SYSDATETIME() function to store the current time 对于ts​​_inserted值,我们使用SYSDATETIME()函数存储当前时间

After executing the procedure, using the statement:

执行该过程后,使用以下语句:

EXEC p_customer_insert "New customer", 1, "New Address", NULL;

the new row was added. We’ll check what is in the table by calling the first procedure we’ve created:

新行已添加。 我们将通过调用我们创建的第一个过程来检查表中的内容:

EXEC p_customer_all;

The last procedure, we’ll analyze today is the one to delete a row using the id passed as parameter. Let’s create the procedure first.

今天我们要分析的最后一个过程是使用作为参数传递的id删除行的过程 。 让我们首先创建过程。

DROP PROCEDURE IF EXISTS p_customer_delete;
GO
CREATE PROCEDURE p_customer_delete (@id INT)
-- procedure deletes the row for the given id
AS BEGINDELETEFROM customerWHERE id = @id;
END;

Once again, we’ve followed the same naming convention when giving the name to our procedure. We pass only 1 parameter and that is the id of the row to delete. Let’s call the procedure now:

再次,当给过程命名时,我们遵循相同的命名约定。 我们仅传递1个参数,这是要删除的行的ID。 现在调用该过程:

EXEC p_customer_delete 6;

This deleted the row with id 6. Let’s check it again, using our first procedure:

这删除了ID为6的行。让我们使用第一个过程再次进行检查:

We’ve seen 4 examples of how we could use SPs to perform simple database operations. In upcoming articles, we’ll go with more complex stored procedures. But before we do that, let’s comment on the advantages SPs have.

我们已经看到了4个示例,说明如何使用SP来执行简单的数据库操作。 在接下来的文章中,我们将介绍更复杂的存储过程。 但是在此之前,让我们先评论一下SP的优势。

使用存储过程的优点 (Advantages of Using Stored Procedures)

SPs have a lot of advantages. I’ll try to list the most important ones:

SP具有很多优势。 我将尝试列出最重要的一些:

  • Modular programming – If you decide to put all logic inside SPs, you’ll be able to easily create/identify modules/parts of your code in charge of different business operations in your system. This will require using the good naming convention and stick to the internal rules, but the benefits are really great. When you need to change something, you will be able to find the related code faster. When you change that code (SP), the change shall be immediately visible at all places where this SP is called 模块化编程 –如果您决定将所有逻辑放入SP中,则可以轻松创建/识别代码的模块/部分,以负责系统中的不同业务操作。 这将需要使用良好的命名约定并遵守内部规则,但是好处确实很大。 当您需要更改某些内容时,您将能够更快地找到相关代码。 当您更改该代码(SP)时,该更改应在调用此SP的所有位置立即可见
  • Better performance – Stored procedures are parsed and optimized after they are created. Since they are stored, there is no need to parse and optimize them again like that would be the case when not using them. This shall definitely spare some time when executing queries inside the SP 更好的性能 –创建存储过程后,将对其进行解析和优化。 由于已存储它们,因此无需像不使用它们时那样再次解析和优化它们。 在SP内部执行查询时,这肯定会节省一些时间
  • Reducing network traffic – This might not be so important as others, but is still an advantage. When you call an SP, you’ll pass its’ name and parameters. Otherwise, you’ll need to send all the lines of code. In case the SP is pretty complex, this would have a larger impact 减少网络流量 –这可能没有其他人那么重要,但仍然是一个优势。 调用SP时,将传递其名称和参数。 否则,您需要发送所有代码行。 如果SP非常复杂,则会产生较大的影响
  • Security – This one is very important. Just as with other database objects, you can define who can access them and how he can use these objects. You can grant the user permission to execute an SP, even if he doesn’t have permission to use all tables in that procedure. That way, you’ll be able to limit users to use only these objects you want them to use. Besides that, the potential attacker won’t be able to see the structure of your database in the code – he’ll only see the name of the SP you’re calling 安全性 –这一点非常重要。 与其他数据库对象一样,您可以定义谁可以访问它们以及他如何使用这些对象。 您可以授予用户执行SP的权限,即使该用户无权使用该过程中的所有表也是如此。 这样,您将能够限制用户仅使用您希望他们使用的这些对象。 除此之外,潜在的攻击者将无法在代码中看到数据库的结构-他只会看到您正在调用的SP的名称。

结论 (Conclusion)

Today we took a look at another very important database object we have on the disposal – stored procedure. They offer a number of advantages. Maybe the biggest disadvantage would be that you need to take care of a large number of procedures and have a procedure for everything – from the simplest to very complex tasks. Still, a good naming convention and internal organization could easily turn this disadvantage into an advantage (by forcing you to follow the same standards and principles in the whole system + simplifying the documentation and, therefore, greatly increasing the chance that you’ll generate it).

今天,我们看了我们要处理的另一个非常重要的数据库对象-存储过程。 它们具有许多优点。 也许最大的缺点是您需要处理大量的过程并为所有过程(从最简单的任务到非常复杂的任务)建立一个过程。 不过,良好的命名约定和内部组织可以轻松地将此缺点变成优点(通过强迫您在整个系统中遵循相同的标准和原则+简化文档,因此大大增加了生成它的机会)。

目录 (Table of contents)

Learn SQL: CREATE DATABASE & CREATE TABLE Operations
Learn SQL: INSERT INTO TABLE
Learn SQL: Primary Key
Learn SQL: Foreign Key
Learn SQL: SELECT statement
Learn SQL: INNER JOIN vs LEFT JOIN
Learn SQL: SQL Scripts
Learn SQL: Types of relations
Learn SQL: Join multiple tables
Learn SQL: Aggregate Functions
Learn SQL: How to Write a Complex SELECT Query?
Learn SQL: The INFORMATION_SCHEMA Database
Learn SQL: SQL Data Types
Learn SQL: Set Theory
Learn SQL: User-Defined Functions
Learn SQL: User-Defined Stored Procedures
Learn SQL: SQL Views
Learn SQL: SQL Triggers
Learn SQL: Practice SQL Queries
Learn SQL: SQL Query examples
Learn SQL: Create a report manually using SQL queries
Learn SQL: SQL Server date and time functions
Learn SQL: Create SQL Server reports using date and time functions
Learn SQL: SQL Server Pivot Tables
Learn SQL: SQL Server export to Excel
Learn SQL: Intro to SQL Server loops
Learn SQL: SQL Server Cursors
Learn SQL: SQL Best Practices for Deleting and Updating data
Learn SQL: Naming Conventions
学习SQL:CREATE DATABASE&CREATE TABLE操作
学习SQL:插入表
学习SQL:主键
学习SQL:外键
学习SQL:SELECT语句
学习SQL:INNER JOIN与LEFT JOIN
学习SQL:SQL脚本
学习SQL:关系类型
学习SQL:联接多个表
学习SQL:聚合函数
学习SQL:如何编写复杂的SELECT查询?
学习SQL:INFORMATION_SCHEMA数据库
学习SQL:SQL数据类型
学习SQL:集合论
学习SQL:用户定义的函数
学习SQL:用户定义的存储过程
学习SQL:SQL视图
学习SQL:SQL触发器
学习SQL:练习SQL查询
学习SQL:SQL查询示例
学习SQL:使用SQL查询手动创建报告
学习SQL:SQL Server日期和时间函数
学习SQL:使用日期和时间函数创建SQL Server报表
学习SQL:SQL Server数据透视表
学习SQL:将SQL Server导出到Excel
学习SQL:SQL Server循环简介
学习SQL:SQL Server游标
学习SQL:删除和更新数据SQL最佳实践
学习SQL:命名约定

翻译自: https://www.sqlshack.com/learn-sql-user-defined-stored-procedures/

存储过程中定义sql语句

存储过程中定义sql语句_学习SQL:用户定义的存储过程相关推荐

  1. sql select 语句_学习SQL:SELECT语句

    sql select 语句 The SELECT statement is probably the most important SQL command. It's used to return r ...

  2. mysql高效sql语句_高效SQL优化 非常好用的SQL语句优化34条

    高效SQL优化 非常好用的SQL语句优化34条 相关软件相关文章发表评论 来源:2011/2/13 9:38:43字体大小: 作者:佚名点击:576次评论:0次标签: 类型:电子教程大小:8.5M语言 ...

  3. oracle删除唯一索引sql语句_高级SQL之在选择语句中使用更新和删除

    点击蓝字关注我吧 [本文详细介绍了数据库中在选择语句中使用更新和删除的方法,欢迎读者朋友们阅读.转发和收藏!] 1 基本概念 1.1 SQL UPDATE 语句 Update 语句 Update 语句 ...

  4. mybatisplus执行sql语句_[MySQL]sql语句的执行流程

    此篇极客时间专栏<MySQL实战45讲>笔记,文中部分图文来自该专栏. MySQL的执行流程示意图: 大体来说,MySQL可以分为Server层和存储引擎层两部分. Server层包括连接 ...

  5. java分页sql语句_「sql分页」sql语句 实现分页 - seo实验室

    sql分页 sql语句 实现分页 /* 分页思想:比如你要每页获取10条记录,当你显示第5页的记录时, 也就是选取第40条至50条的记录.首先应该从所有的记录集中选取 50条记录,同时进行倒序,再从中 ...

  6. mysql原生sql语句_原生SQL语句

    -- -sql语句的注意 : 1 以;作为结束符 2不区分大小写--01mysql 数据库的操作--链接数据库 mysql-uroot -pmysql--不显示密码 mysql-uroot -p my ...

  7. mysql删除字段sql语句_用SQL语句添加删除修改字段

    用SQL语句添加删除修改字段 1.增加字段 alter table docdsp add dspcode char(200) 2.删除字段 ALTER TABLE table_NAME DROP CO ...

  8. c语言解析sql语句_解析SQL语句比解析类C语言更麻烦?

    最近想做一个SQL语句解析器,换句话说想给自己的系统加上类似SQL语句的查询引擎.我之前做过一个解析类似C语言语法的解析器,可以解析 C/C++里的运算表达式,if-else-等基本语句.我以为做个S ...

  9. 使用了无效的sql语句_使用SQL语句创建数据库

    使用SQL语句创建数据库(SQL Server 2008) 创建一个名为'DA_sales'的数据库. 主文件组'DA_sales_data'(初始大小:5MB;最大值:200MB;自动增长率:10% ...

最新文章

  1. mysql-connector-net-6.7.4.msi,在ActiveReports中使用MySQL数据库
  2. Oracle管理拾遗(长期更新)
  3. MATLAB之离散时间傅里叶变换DTFT
  4. rust-let 不可变绑定与可变绑定(4)
  5. proteus跑马灯仿真_不花费一分钱,实现跑马灯编程实验
  6. Exceptionless 5.0.0本地Docker快速部署介绍
  7. GatewayMetricsFilter网关度量过滤器(服务监控)
  8. 从草根到百万年薪程序员的十年风雨之路,吊打面试官系列!
  9. LeetCode MySQL 602. 好友申请 II :谁有最多的好友(union all)
  10. 网站页面增加一个简单的密码登录访问php网站源码
  11. 盈利靠涨价、广告满屏飞,共享充电宝入局容易做大难
  12. ASP网页中 制作连续无缝滚动文字
  13. MYSQL服务器my.cnf配置文档详解
  14. vba 数组填充单元格
  15. LG V50救砖教程
  16. 毕业论文选题方法和论文各部分写作技巧
  17. 设计模式学习 - 观察者模式
  18. 笑傲江湖 琴箫合奏之曲
  19. Word插入Latex公式的几种方式~(TeXsWord、EqualX、Aurora、向Office插入LaTeX公式的工具)...
  20. 制造业增值税从16%下降到13%,我们是否应该降价出售?

热门文章

  1. plc模拟器软件_你的PLC和触摸屏为什么总是通讯不上?
  2. Chromium内核原理之网络栈HTTP Cache
  3. Joseph_Circle(约瑟夫环)
  4. Game HDU - 5242 树链思想
  5. UOJ 7 NOI2014 购票
  6. matlab中输入x. 与x的区别
  7. centos7安装telnet服务
  8. nlog自定义文件名
  9. 17011301(UE4的AnimDynamic)
  10. 浅谈Hybrid技术的设计与实现第二弹