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.

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

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
BEGINSQL statementsRETURN value
END;ALTER FUNCTION [database_name.]function_name (parameters)
RETURNS data_type AS
BEGINSQL statementsRETURN 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
BEGINDECLARE @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).

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

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.

结果如下图所示。

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;

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
RETURNSELECT *FROM cityWHERE city.long > @long;

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

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

Now, we’ll use the function.

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

SELECT *
FROM east_from_long(0.00);

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

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

  1. android sqlite自定义函数,如何在SQLite中创建用户定义的函数?

    SQLite不像Oracle或MS SQL Server那样支持用户定义的功能.对于SQLite,必须使用C / C ++创建一个回调函数,并使用sqlite3_create_function调用将该 ...

  2. sql:命名管道管道程序_学习SQL:命名约定

    sql:命名管道管道程序 A naming convention is a set of unwritten rules you should use if you want to increase ...

  3. sql学习练习题_学习SQL:练习SQL查询

    sql学习练习题 Today is the day for SQL practice #1. In this series, so far, we've covered most important ...

  4. sql 左联接 全联接_学习SQL:联接多个表

    sql 左联接 全联接 If you want to get something meaningful out of data, you'll almost always need to join m ...

  5. SQL SERVER中用户定义标量函数(scalar user defined function)的性能问题

    SQL SERVER中用户定义标量函数(scalar user defined function)的性能问题 原文:SQL SERVER中用户定义标量函数(scalar user defined fu ...

  6. 自定义按钮动态变化_新闻价值的变化定义

    自定义按钮动态变化 I read Bari Weiss' resignation letter from the New York Times with some perplexity. In par ...

  7. 可以在一个函数中定义另一个函数_第5周 定义一个函数

    亲爱的观众老爷们,早上好! 编程大师Martin Fowler先生曾经说过:"代码有很多种坏味道,重复是最坏的一种!",要写出高质量的代码首先要解决的就是重复代码的问题. 那么有什 ...

  8. 找不到列 dbo 或用户定义的函数或聚合 dbo xxx ,或者名称不明确

    MSSQL执行查询错误提示:找不到列 "dbo" 或用户定义的函数或聚合 "dbo.xxx",或者名称不明确. 错误原因及解决办法: 原因1:数据库中不存在这个 ...

  9. 执行xpath时提示,需要命名空间管理器或XsltContext。此查询具有前缀、变量或用户定义的函数

    执行xpath时提示,需要命名空间管理器或XsltContext.此查询具有前缀.变量或用户定义的函数 2012-05-05 10:45:48|  分类: 默认分类 |  标签:要命名空间管理器  x ...

最新文章

  1. poj1129Channel Allocation
  2. CTFshow php特性 web134
  3. java反射有什么用_java反射的作用知识点总结
  4. nmake错误:VC\bin\cl.EXE: 返回代码“0xc0000135“
  5. AI又抢了人类职位,这回轮到银行销售人员了?
  6. python 面向对象的封装_Python面向对象封装操作案例详解
  7. 佳能G3800黄灯绿灯交替闪烁7次,错误代码5B00
  8. CarMaker试用版许可证申请与软件安装过程
  9. 微信网页授权失败原因总结
  10. 惠普笔记本触摸板失灵
  11. 测试固态硬盘写入数据软件,持续写入100TB 三星840EVO耐久度测试
  12. Win10安全证书过期怎么办
  13. 8 . STM32固件库介绍
  14. 块级、内联、内联块级
  15. [openstack swift]0 swift介绍
  16. 百度语音合成模型Deep Voice3
  17. 深度学习——深度学习基础概念
  18. 上传项目到开源中国码云
  19. JavaGUI小结——实验做的QQ登录界面
  20. Access2003中自定义菜单栏

热门文章

  1. 在线修改Schema
  2. java 程序打成.exe可执行程序
  3. Oracle数据库安装图文操作步骤
  4. Linux自动化运维第十八课
  5. Android深度探索-卷1第二章心得体会
  6. 027_编写MapReduce的模板类Mapper、Reducer和Driver
  7. Sharepoint CAML 增删改查 List
  8. [学习笔记] 七步从AngularJS菜鸟到专家(6):服务 [转]
  9. [导入]XI 常用的URL
  10. JavaScript学习(二十三)—scrollTop练习