说我有一个带有文本数组参数TEXT []的函数。如果执行EXECUTE FORMAT INSERT,如何传递该数组的带引号的文本字符串以插入?
答案 0 :(得分:1)
您应该使用USING
子句。动态SQL可以在通常的地方使用参数(非SQL标识符):
CREATE TABLE foo(a varchar[]);
CREATE OR REPLACE FUNCTION public.fx(tblname text, VARIADIC p character varying[])
RETURNS void LANGUAGE plpgsql AS $function$
BEGIN
EXECUTE format('insert into %I(a) VALUES($1)', tblname) USING p;
END;
$function$
SELECT fx('foo', 'Hi','Hello');
SELECT fx('foo', 'Hi','Hel''lo');
SELECT fx('foo', 'Hi','Hel"lo');
postgres=# SELECT * FROM foo;
┌────────────────┐
│ a │
╞════════════════╡
│ {Hi,Hel'lo} │
│ {Hi,"Hel\"lo"} │
│ {Hi,Hello} │
└────────────────┘
(3 rows)
答案 1 :(得分:0)
谢谢,我现在知道何时使用using和格式。这是我修改后的代码:
CREATE OR REPLACE FUNCTION add_property(catid INT, colname TEXT,
ty catalog_column_type, colval TEXT[])
RETURNS jsonb AS $$
DECLARE
tn TEXT;
BEGIN
--check table exists
SELECT tablename INTO tn FROM catalog WHERE catalogid=catid;
IF NOT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_name=tn)
THEN
return jsonb_build_object('error','notable');
END IF;
--check if property exists for table
IF EXISTS(SELECT 1 FROM catalog_columns WHERE catalogid=catid AND
columnname=colname) THEN
return jsonb_build_object('error','exists');
END IF;
IF ty='INT'::catalog_column_type THEN
EXECUTE FORMAT ('ALTER TABLE %I ADD COLUMN %I INT',tn,colname);
ELSIF ty='TEXT'::catalog_column_type THEN
EXECUTE FORMAT ('ALTER TABLE %I ADD COLUMN %I TEXT',tn,colname);
ELSIF ty='ENUM'::catalog_column_type THEN
EXECUTE FORMAT ('ALTER TABLE %I ADD COLUMN %I INT',tn,colname);
ELSIF ty='BOOLEAN'::catalog_column_type THEN
EXECUTE FORMAT ('ALTER TABLE %I ADD COLUMN %I BOOLEAN',tn,colname);
END IF;
EXECUTE 'INSERT INTO catalog_columns (catalogid,columnname,'
|| 'columntype,columnnvalues) VALUES ($1,$2,$3,$4)' USING catid,colname,
ty,colval;
return jsonb_build_object('error','OK');
END;
$$ LANGUAGE plpgsql;