sql自定义函数学习思路_学习SQL:用户定义的函数

sql自定义函数学习思路

You can create several user-defined objects in a database. One of these is definitely user-defined functions. When used as intended, they are a very powerful tool in databases. In today’s article, we’ll see how to create, change and remove them from the database, as well as how to use them. So, let’s dive into the matter.

您可以在数据库中创建多个用户定义的对象。 其中之一绝对是用户定义的功能。 当按预期使用时,它们是数据库中非常强大的工具。 在今天的文章中,我们将看到如何在数据库中创建,更改和删除它们,以及如何使用它们。 因此,让我们深入探讨这个问题。

SQL Server对象 (SQL Server Objects)

As mentioned in the introduction, there are different kinds of objects you could create in the database. Besides tables and keys, other well-known objects are procedures, triggers, and views. And, of course, user-defined functions, which are today’s topic. The main idea behind objects is to have them stored in the database and avoid writing the same code over and over again. Also, you can control what is the input and define the structure/type of output. And last, but not least, you can define permissions to decide who’ll be able to use them and in what way he’ll be able to do it.

如简介中所述,您可以在数据库中创建各种对象。 除了表和键之外,其他知名对象还有过程,触发器和视图。 当然还有用户定义的功能,它们是当今的话题。 对象背后的主要思想是将它们存储在数据库中,并避免一遍又一遍地编写相同的代码。 另外,您可以控制什么是输入并定义输出的结构/类型。 最后但并非最不重要的一点是,您可以定义权限来决定谁可以使用它们以及他将以哪种方式使用它。

We’ll describe all of them in the upcoming articles, but in this article, we’ll focus only on the user-defined functions.

我们将在接下来的文章中描述所有这些内容,但是在本文中,我们将仅关注用户定义的函数。

该模型 (The Model)

Let’s remind ourselves of the model we’re using in this article series.

让我们回想一下本系列文章中使用的模型。

The data model we'll use to explain user-defined functions

This time we won’t use this model so extensively as before, because of the nature of the functions we’ll declare, but also because of the complexity of queries we’ll use (they’ll be much simpler). While our queries will be simple, there is no reason why you wouldn’t use user-defined functions in much more complex queries as well.

这次,由于我们将声明的函数的性质,而且由于我们将使用的查询的复杂性(它们会简单得多),因此我们不会像以前那样广泛地使用此模型。 虽然我们的查询很简单,但是没有理由不在更复杂的查询中也不使用用户定义的函数。

CREATE / ALTER / DROP用户定义的功能 (CREATE/ALTER/DROP User-Defined Function)

Whenever you’re working with database objects, you’ll use these commands – CREATE (new), ALTER (existing), and DROP (existing). The syntax goes something like CREATE/ALTER/DROP <type of the database object> <object name> AS. This differs slightly regarding the object type and also if you are creating, modifying or deleting the object.

每当使用数据库对象时,都将使用以下命令-CREATE(新),ALTER(现有)和DROP(现有)。 语法类似于CREATE / ALTER / DROP <数据库对象的类型> <对象名称> AS。 这在对象类型以及创建,修改或删除对象方面略有不同。

For user-defined functions, these syntaxes look as follows:

对于用户定义的函数,这些语法如下所示:

CREATE FUNCTION [database_name.]function_name (parameters)
RETURNS data_type AS
BEGIN
    SQL statements
    RETURN value
END;
    
ALTER FUNCTION [database_name.]function_name (parameters)
RETURNS data_type AS
BEGIN
    SQL statements
    RETURN value
END;
    
DROP FUNCTION [database_name.]function_name;

Most things should be pretty obvious here. The function:

大多数事情在这里应该很明显。 功能:

  • parameters as input 参数作为输入
  • SQL statements). Technically it will use values provided as parameters and combine them with other values (local variables) or database objects and then return the result of these combinations/calculations SQL语句)执行某些操作。 从技术上讲,它将使用提供的值作为参数并将它们与其他值(局部变量)或数据库对象组合,然后返回这些组合/计算的结果
  • RETURN value) with the previously defined type (RETURNS data_type)的计算结果( RETURNS data_type) RETURN值

ALTER is very similar to CREATE and it simply modifies the existing function. To delete a function, we’ll use statement DROP FUNCTION and the name of that function.

ALTER与CREATE非常相似,它只是修改现有功能。 要删除一个函数,我们将使用语句DROP FUNCTION和该函数的名称。

  • Note: If we would work with procedures, we would use CREATE PROCEDURE, ALTER PROCEDURE, and DROP PROCEDURE.注意:如果要使用过程,则将使用CREATE PROCEDURE,ALTER PROCEDURE和DROP PROCEDURE。

一个简单的用户定义功能 (A Simple User-Defined Function)

It’s time that we create our first and pretty simple user-defined function. We want to list all cities and write down are they east or west when compared to London (longitude = 0). Cities east of London will have positive city.long values, while those west of London will have this value negative.

是时候创建第一个也是非常简单的用户定义函数了。 我们要列出所有城市,并记下与伦敦相比(经度= 0)是东方还是西方。 伦敦以东的城市将具有正的long.long值,而伦敦以西的城市将具有负的value.long值。

We’ll use the following code to create the function:

我们将使用以下代码创建该函数:

CREATE FUNCTION east_or_west (
	@long DECIMAL(9,6)
)
RETURNS CHAR(4) AS
BEGIN
	DECLARE @return_value CHAR(4);
	SET @return_value = 'same';
    IF (@long > 0.00) SET @return_value = 'east';
    IF (@long < 0.00) SET @return_value = 'west';
 
    RETURN @return_value
END;

The first thing we should notice, after running this command, is that our function is now visible when we expand “Scalar valued functions” in the “Object Explorer” (for the database where we’ve created this function).

运行此命令后,我们首先要注意的是,当我们在“对象资源管理器”中(对于创建此函数的数据库中)扩展“标量值函数”时,我们的函数现在可见。

Object explorer scalar-valued functions

Our function takes a number as a parameter. The return value must be of the CHAR(4) type. The initial value (variable @return_value) is initially set to ‘same’. If the parameter (variable @long) is greater than 0, we’re ‘east’ from London, and if it’s less than 0, we’re ‘west’ of London. Notice that, in case of @long was 0, none of these two Ifs will change the value, so it will hold the initial value -> ‘same’.

我们的函数将数字作为参数。 返回值必须是CHAR(4)类型。 初始值(变量@return_value)最初设置为'same' 。 如果参数(变量@long)大于0,则表明我们位于伦敦的“东边” ;如果小于0,则表明我们位于伦敦的“西边” 。 注意,在@long为0的情况下,这两个If都不会更改该值,因此它将保留初始值-> 'same'

This is really a simple function, but it’s a nice way to show what functions can do.

这确实是一个简单的函数,但这是显示函数可以执行的一种好方法。

Let’s now see how we can use this function inside a query. To achieve that, we’ll use the following simple select statement:

现在让我们看看如何在查询中使用此函数。 为此,我们将使用以下简单的select语句:

SELECT dbo.east_or_west(0) AS argument_0, dbo.east_or_west(-1) AS argument_minus_1, dbo.east_or_west(1) AS argument_plus_1;

The result is shown in the picture below.

结果如下图所示。

Testing function

You can easily notice that we’ve called function 3 times in the same select, and the output was as expected. This was actually testing if our function is working as expected.

您可以很容易地注意到,我们在同一选择中调用了3次函数,并且输出与预期的一样。 这实际上是在测试我们的功能是否按预期工作。

  • Note: You’ll call a function by simply using its name and providing the parameters needed. If the function is value-based, then you’ll be able to use this function at any place where you would use a number, string, etc.注意:您可以通过简单地使用函数名称并提供所需的参数来调用该函数。 如果该函数基于值,那么您将可以在任何使用数字,字符串等的地方使用此函数。

Now, we’ll use this function in the more complex query:

现在,我们将在更复杂的查询中使用此函数:

SELECT *, dbo.east_or_west(city.long) 
FROM city;

SELECT query result

The important thing to notice here is that we’ve used function as a “column” in our select query. We’ve passed parameter (city.long of the related row) and the function returned a result of the calculation. This is great because we’ve avoided writing complex calculations in a select query, and also, we can reuse this function later in any other query.

在此需要注意的重要一点是,在选择查询中,我们已将函数用作“列”。 我们已经传递了参数(相关行的city.long ),并且该函数返回了计算结果。 这非常好,因为我们避免了在选择查询中编写复杂的计算,而且以后可以在任何其他查询中重用此函数。

  • Note: Creating a user-defined function has few advantages:

    注意:创建用户定义的函数有几个优点:

  • Complex code is stored in one structure. You can later look at that structure as on the black box, where you’re only interested in passing appropriate values as parameters and the function will do the rest

    复杂代码存储在一种结构中。 稍后,您可以像在黑匣子上那样查看该结构,您只对传递适当的值作为参数感兴趣,其余的将由函数完成
  • You can much easier test input parameters using IF or CASE, and even use loops in the functions. This is sometimes very hard (sometimes impossible) to simulate directly in SELECT statements

    您可以使用IF或CASE轻松测试输入参数,甚至在函数中使用循环。 有时很难直接在SELECT语句中进行模拟(有时是不可能的)
  • Once you create a function, and after it’s properly tested, you don’t have to bother later is it working as expected and you’re avoiding a possibility to make an error because you’re not rewriting the same code over and over again (not to mention that you’ll use less time when not rewriting the same code)

    创建函数并经过正确测试后,您以后就不必再为它按预期工作而烦恼了,并且避免了出错的可能性,因为您不必一次又一次地重写相同的代码(更不用说在不重写相同代码的情况下,您将花费更少的时间)
  • If you need to make changes to your code, you’ll do it in one place and it will reflect at every place this function is used

    如果您需要更改代码,则将其放在一个地方,它将在使用该函数的每个地方反映出来

用户定义的函数返回表 (A User-Defined Function Returning the Table)

Let’s now examine a more complex function. This time we want to pass long as an argument and we’ll expect that function returns a table of all cities ‘east’ from the given parameter.

现在让我们研究一个更复杂的功能。 这次,我们希望将传递的时间作为参数,并且期望该函数返回给定参数“东”的所有城市的表格。

We’ve created the following function:

我们创建了以下函数:

CREATE FUNCTION east_from_long (
	@long DECIMAL(9,6)
)
RETURNS TABLE AS
RETURN
	SELECT *
	FROM city
	WHERE city.long > @long;

You can also see that function listed in the “Table-valued Functions” section in the “Object Explorer”.

您还可以在“对象资源管理器”的“表值函数”部分中看到该函数。

Object explorer table-valued functions

Now, we’ll use the function.

现在,我们将使用该函数。

SELECT *
FROM east_from_long(0.00);

User-defined function used in the FROM part of the SELECT query

You can notice that we’ve used the function as a table (it’s a table-valued function, so this sounds pretty logical 🙂 ).

您会注意到我们已经将该函数用作表(这是一个表值函数,因此听起来很合逻辑🙂)。

实施思路 (An idea to implement)

I won’t do it now, but just throwing out an idea. This is something that’s doable in other ways (GROUP_CONCAT or simulating it), but the function and loops would really help here a lot. So, the thing we want to do is following – Write down a function that shall, for a given city.id, find all cities east and west from that city. The function shall return a string like “east: <names of all cities east from the given city>; west: <names of all cities west from the given city>”. You should use a loop in this function. You can Google it or wait for our article related to loops in SQL Server.

我现在不会这样做,只是抛出一个想法。 这可以通过其他方式(GROUP_CONCAT或模拟它)来完成,但是函数和循环确实可以在很大程度上帮助您。 因此,我们要做的是-编写一个函数,该函数对于给定的city.id,应查找该城市以东和以西的所有城市。 该函数应返回一个字符串,例如“ east:<给定城市以东的所有城市的名称>; 西方:<指定城市以西的所有城市的名称>” 。 您应该在此函数中使用循环。 您可以对其进行Google搜索或等待我们与SQL Server中的循环相关的文章。

结论 (Conclusion)

User-defined functions are a very powerful tool. You should use them when you’ll have a calculation you’ll repeat throughout your database. E.g. calculating the tax on different products based on predefined rules (that can change during the time), is one good candidate for the function. You put all rules there, pass parameters to the function, and as a result get the desired number. But, as with everything else, do not overuse them.

用户定义的功能是一个非常强大的工具。 在进行计算时,应使用它们,并在整个数据库中重复进行计算。 例如,根据预定义的规则(可以随时间变化)对不同产品计算税款,是该功能的一个很好的候选者。 您将所有规则放在此处,将参数传递给该函数,结果得到所需的数字。 但是,与其他所有内容一样,请勿过度使用它们。

目录 (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-functions/

sql自定义函数学习思路

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值