GaussDB database SQL series-custom function

Table of contents

I. Introduction

2. Overview of custom functions (Function)

3. Usage scenarios

4. Advantages and Disadvantages

1. Advantages of using Function in database

2. Disadvantages of using Function in the database

5. Function examples and analysis in GaussDB

1. Example 1: Define function as SQL query

2. Example 2: Return a record containing multiple output parameters

3. Example 3: Return RECORD type result set

6. Summary

I. Introduction

Huawei Cloud GaussDB database is a high-performance, high-security cloud-native database. In GaussDB, custom functions are an important feature that cannot be ignored. This article will briefly introduce the usage scenarios of custom functions in GaussDB, their advantages and disadvantages, examples and sample analysis, etc., to provide guidance and help to readers.

2. Overview of custom functions (Function)

In SQL, a custom function (Function) is a reusable block of code that performs a specific task and returns a result. Function can accept parameters and can return specified results, etc. In GaussDB, Function is an important "tool" for database managers and developers. Through Function, complex logic can be encapsulated to simplify the data processing process and improve work efficiency.

3. Usage scenarios

Usage scenarios of Function in the database include but are not limited to the following, for example:

  • Data processing: can be used to process data, such as splitting, merging, replacing, converting strings, etc.; formatting dates and times, calculating time differences, etc.; calculating, rounding, rounding, etc. Operation; perform logical operations on Boolean values, etc.
  • Aggregation operations: can be used to perform aggregation operations on data, such as calculating average, sum, maximum, minimum, etc.
  • Conditional judgment: It can be used to perform conditional judgment, such as judging whether a value meets a specific condition and returning the corresponding result.
  • Implement code reuse and abstraction: It can be used to implement code reuse, thereby reducing the programmer's workload of writing duplicate code, and can also be used to implement code abstraction.

4. Advantages and Disadvantages

1. Advantages of using Function in database

  • Fast execution speed: It is only compiled when it is created, and does not need to be recompiled every time it is executed. Generally, SQL statements need to be compiled every time they are executed, so using functions can improve the execution speed of the database.
  • Easy to operate: Complex database operations can be encapsulated, and only one function call is needed to complete the corresponding operation, thus simplifying database operations.
  • High reusability: It can be used repeatedly, reducing the workload of database developers.
  • Improve system security: You can set that only specific users have the right to use specified functions, which enhances database security.

2. Disadvantages of using Function in the database

  • Difficulty in Debugging : Compared to SQL statements, functions are more difficult to debug.
  • Poor portability : In different database systems, the usage and syntax of functions may be different, so functions are less portable.

5. Function examples and analysis in GaussDB

Common Function operations (create, call, delete, etc.)

1. Example 1: Define function as SQL query

--定义函数为SQL查询
CREATE FUNCTION func_add_sql(integer, integer) RETURNS integer
    AS 'select $1 + $2;'
    LANGUAGE SQL
    IMMUTABLE
RETURNS NULL ON NULL INPUT;

--调用
SELECT func_add_sql(1,9);

--DROP
DROP FUNCTION func_add_sql;

Call result:

Analysis description:

This code is creating a SQL function called 'func_add_sql', which accepts two integers as input parameters and returns their sum.

  • "CREATE FUNCTION": This is a SQL command used to create a new function.
  • "func_add_sql": This is the name of the function created.
  • "RETURNS integer": This specifies that the return type of the function is an integer.
  • "IMMUTABLE": This is a feature that indicates that this function always returns the same result when given the same input. That is, this function does not depend on any external state or data, and its results do not change.
  • "RETURNS NULL ON NULL INPUT": Indicates that if any input parameter is NULL, the function will return NULL.
  • "LANGUAGE SQL": This specifies that the function is written in SQL language.
  • "'select $1 + $2;'": This is the body of the function. $1 and $2 are parameter references, representing the two input parameters respectively.

2. Example 2: Return a record containing multiple output parameters

--返回一个包含多个输出参数的记录。
CREATE FUNCTION func_dup_sql(in int, out f1 int, out f2 text)
    AS $$ SELECT $1, CAST($1 AS text) || ' is text' $$
    LANGUAGE SQL;

--调用
SELECT * FROM func_dup_sql(10);

--DROP
DROP FUNCTION func_dup_sql;

Call result:

Analysis description:

This function is called func_dup_sql, it accepts one input parameter (labeled in), and produces two outputs (labeled f1 and f2).

The code block is marked with $$ inside the function body. Inside is a SELECT statement, which returns two different values ​​of the input parameter $1. For f1, it returns the input integer value directly. For f2, it converts the input integer value to a text string and appends the string 'is text' after it. This conversion is done using the CAST function, which converts $1 from an integer value to a text string.

The language of this function is SQL, which means that it is executed in the context of SQL. Basically, this function takes an integer as input and returns two values: an integer and a string generated from the integer with a text suffix added.

3. Example 3: Return RECORD type result set

--返回RECORD类型
CREATE OR REPLACE FUNCTION compute(i int, out result_1 bigint, out result_2 bigint)
returns SETOF RECORD
as $$
begin
    result_1 = i + 1;
    result_2 = i * 10;
return next;
end;
$$ language plpgsql;

--调用
SELECT compute(10);

--DROP
DROP FUNCTION compute;

Call result:

Analysis description:

This is a definition of a GaussDB database compatible PL/pgSQL custom function. This function is called compute, it accepts an integer parameter i, and returns a recordset containing two fields: result_1 and result_2, both of which are big integer types (bigint).

In the body of the function, the following operations are defined:

  • "result_1 = i + 1;": Assign the result of adding 1 to parameter i to result_1.
  • "result_2 = i * 10;": Assign the result of multiplying parameter i by 10 to result_2.
  • "return next;": Returns the next row in the result set. Since this function only returns one row, this row will be returned on the first call.
  • "$$ language plpgsql;" : Declares that the programming language of this function is compatible with PL/pgSQL.

When calling this function, you can pass in an integer parameter, and it will return a result set containing a record whose result_1 field value is the input integer plus 1, and the result_2 field value is the input integer multiplied by 10.

6. Summary

In general, in GaussDB, functions are a powerful and flexible tool that can help database managers and developers process and operate data more effectively, improve work efficiency, and perform data query, data conversion, data filtering, etc. play a greater role in the scene.

Of course, regarding the GaussDB database, there are many practices in addition to the above examples, such as: creating overloaded functions of the package attribute, modifying functions through the syntax "ALTER FUNCTION function_name...", and deleting through the syntax "DROP FUNCTION [ IF EXISTS ] function_name..." Functions, etc. You are welcome to refer to the official website information for study and testing!

--Finish

Fined 200 yuan and more than 1 million yuan confiscated You Yuxi: The importance of high-quality Chinese documents Musk’s hard-core migration of servers TCP congestion control saved the Internet Apache OpenOffice is a de facto “unmaintained” project Google celebrates its 25th anniversary Microsoft open source windows-drivers-rs, use Rust to develop Windows drivers Raspberry Pi 5 will be released at the end of October, priced from $60 macOS Containers: Use Docker to run macOS images on macOS IntelliJ IDEA 2023.3 EAP released
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/gaussdb/blog/10114789