Chuyển đến nội dung chính
eLearner.app
Mô-đun 12 · Bài học 1 trong tổng số 445/57 trong khóa học~15 min
Bài học theo mô-đun (1/4)

UDF và SQL cơ sở

So far we've been sending queries from the Node.js server. But if a formula is used in dozens of different queries (e.g. computing the final price including VAT), why duplicate the math in JavaScript? SQL Functions (User Defined Functions - UDF) let us create "macros" inside the DB itself.

Here is how to create a mathematical SQL macro:

SQL
CREATE OR REPLACE FUNCTION calculate_tax(price NUMERIC)
RETURNS NUMERIC AS $$
  SELECT price * 1.22;
$$ LANGUAGE sql;

Once this command runs, the function lives forever in our database. It can be called from any query:

SQL
SELECT name, calculate_tax(unit_price) AS price_with_tax FROM products;

Dynamic creation

We can define as many variables as we want, specifying their types, and LANGUAGE sql will run the query and implicitly return the last statement placed between the dollar signs $$.

Try it yourself

tập thể dục#sql.m12.l1.e1
Nỗ lực: 0Đang tải…

Create a simple callable function named 'get_full_name' that accepts two TEXT parameters ('first_name' TEXT, 'last_name' TEXT).\nIt must return a TEXT value.\nInside, do a trivial SELECT that concatenates the two arguments with a single space between them, and declare it as language sql.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

CREATE OR REPLACE FUNCTION get_full_name(first_name TEXT, last_name TEXT) RETURNS TEXT AS $$ SELECT first_name || ' ' || last_name; $$ LANGUAGE sql;

Giải pháp khả dụng sau 3 lần thử

tập thể dục#sql.m12.l1.e2
Nỗ lực: 0Đang tải…

In more advanced UDFs we can embed entire queries. Create a function 'get_customer_count()' that accepts no parameters and RETURNS an INTEGER.\nInside, run a trivial 'SELECT COUNT(id) FROM customers'.\nDeclare it as pure sql language.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Watch out: COUNT returns a bigint, cast it to INTEGER to match the return type! CREATE OR REPLACE FUNCTION get_customer_count() RETURNS INTEGER AS $$ SELECT CAST(COUNT(id) AS INTEGER) FROM customers; $$ LANGUAGE sql;

Giải pháp khả dụng sau 3 lần thử