Available in versions: 可用版本: Dev (3.21) | Latest (3.20) 最新 (3.20) | 3.19 | 3.18 | 3.17 | 3.16 | 3.15

标量函数

适用于 ❌ 开源版   ✅ Express 版   ✅ 专业版   ✅ 企业版

The most common type of user defined function (用户自定义函数) is a scalar function (标量函数), i.e. a function that returns a single scalar value (返回单个标量值的函数). Such functions can be used in the SELECT clause (SELECT 子句), the WHERE clause (WHERE 子句), the GROUP BY clause (GROUP BY 子句), the HAVING clause (HAVING 子句), the ORDER BY clause (ORDER BY 子句), and elsewhere, where column expressions (列表达式) can be used.

A simple example for creating such a function is 创建此类函数的简单示例是

// Create a function that always return 1
create.createFunction("one")
      .returns(INTEGER)
      .as(return_(1))
      .execute();

// Create a function that returns the sum of its inputs
Parameter<Integer> i1 = in("i1", INTEGER);
Parameter<Integer> i2 = in("i2", INTEGER);

create.createFunction("my_sum")
      .parameters(i1, i2)
      .returns(INTEGER)
      .as(return_(i1.plus(i2)))
      .execute();

Once you've created the above functions, you can either run code generation to get a type safe stub for calling them, or use 一旦您创建了上述函数,您可以运行代码生成来获取类型安全的存根来调用它们,或者使用plain SQL (原始 SQL) (specifically, (特别是) DSL.function()) from within a (从) SELECT statement (SELECT 语句)

// Call the previously created functions with generated code:
create.select(one(), mySum(1, 2)).fetchOne();

// ...or with plain SQL
create.select(
  function(name("one"), INTEGER),
  function(name("my_sum"), INTEGER, val(1), val(2))
).fetchOne();

Both yielding 两者都产生

+-----+--------+
| ONE | MY_SUM |
+-----+--------+
|   1 |      3 |
+-----+--------+

引用此页

反馈

Do you have any feedback about this page? 您对此页面有任何反馈吗?We'd love to hear it! (我们很乐意听到!)

The jOOQ Logo