如何编写 SQL 函数以减少代码重复

cge*_*get 3 sql google-bigquery

我需要为多个国家/地区运行 SQL 函数

我想知道是否有一种方法可以创建一个函数,我可以在其中输入国家/地区名称并为每个国家/地区获取一个表格。这是我对德国的查询

SELECT customer.id,
       product_purchased,
       country
FROM sales_tables
WHERE country = 'Germany'
Run Code Online (Sandbox Code Playgroud)

所以我可以做这样的事情而不是改变代码中的每个国家

FUNCTION products_purchased_byCountry($1):
    SELECT customer.id,
           product_purchased,
           country
    FROM sales_tables
    WHERE country = '$1'
Run Code Online (Sandbox Code Playgroud)

然后只需使用以下命令调用此函数

products_purchased_byCountry(Germany)
products_purchased_byCountry(France)
products_purchased_byCountry(UK)
Run Code Online (Sandbox Code Playgroud)

或者也许要运行这样的函数,我必须通过 R 或 Python 来完成?

小智 5

您可以使用存储过程并将@country 设置为变量。

Create procedure products_purchased_byCountry

@country varchar(100)

AS BEGIN

SELECT customer.id,
       product_purchased,
       country
FROM sales_tables
WHERE country = @country

END
Run Code Online (Sandbox Code Playgroud)

然后这样调用

EXEC products_purchased_byCountry 
@country = 'Germany'
Run Code Online (Sandbox Code Playgroud)