postgresql - 我需要捕获所有 product_id 以便我可以在 sql in 子句中使用它
问题描述
CREATE OR replace FUNCTION testfunction(timestamp) returns void
AS
$body$
DECLARE
product_ids text;
BEGIN
-- this is returning multiple rows, but it assigning only one to prodcut_ids variable.
SELECT DISTINCT product_id AS product_id
INTO product_ids
FROM test_product
WHERE created_on > $1::timestamp
ORDER BY product_id ;
RAISE notice 'product IDs : %', product_ids;
EXECUTE 'copy (SELECT * FROM test_product WHERE product_id in ('
|| product_ids
|| ' ) ) TO ''C:\projects\test_product.csv'' CSV HEADER';
END $body$ LANGUAGE plpgsql volatile;
-- it is only exporting one record even the above select returning
多行。
解决方案
将条件直接放在EXECUTE
. 出于显示目的,用于STRING_AGG
显示逗号分隔的 product_ids。
CREATE OR replace FUNCTION testfunction ( timestamp ) returns void
AS
$body$
DECLARE
v_created_on timestamp := $1;
BEGIN
SELECT STRING_AGG( product_id,',' ORDER BY product_id)
INTO product_ids
FROM test_product
WHERE created_on > v_created_on;
RAISE notice 'product IDs : %', product_ids;
EXECUTE 'copy ( SELECT * FROM test_product WHERE created_on > $1 )
TO ''C:\projects\test_product.csv'' CSV HEADER' USING v_created_on;
END;
$body$ LANGUAGE plpgsql volatile;
推荐阅读
- c++ - 我需要编写一个具有这些目标的 c++ 程序
- php - 无法使用 $wpdb 访问 wordpress 数据库
- wordpress - 如何通过 FTP 上传更改的文件?(wordpress)
- matplotlib - 如何使用 timstamp 和坐标进行绘图?
- php - Artisan::call 命令包抛出错误异常将通过网页调用
- validation - LUA 信用卡有效期验证
- docker - 如何在创建 docker 映像时将 jdk 挂载到卷中并在容器中使用它
- python - 如何在没有 matlab 的情况下将 v 7.3 的 .mat 文件转换为 excel 或 csv?
- ios - 在 Swift 中将 %1$s 等占位符转换为 {x}
- r - 防止 withSpinner 默认出现