我使用以下select语句来检索我需要处理的列数据:
SELECT c.table_schema, c.table_name, c.column_name, c.column_default, c.data_type, c.udt_name,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name
FROM information_schema.columns AS c
LEFT JOIN information_schema.key_column_usage AS kcu
ON c.table_name = kcu.table_name AND c.column_name = kcu.column_name
LEFT JOIN information_schema.constraint_column_usage as ccu
ON kcu.constraint_name = ccu.constraint_name
WHERE c.table_name = 'mytable'
现在我需要循环这个select语句的结果。我这样做:
CREATE OR REPLACE FUNCTION public.myfunction(tableName CHARACTER VARYING(18), rows NUMERIC(10))
RETURNS VOID AS $BODY$
DECLARE
r ( table_schema varchar,
table_name varchar,
column_name varchar,
column_default varchar,
data_type varchar,
udt_name varchar,
foreign_table_name varchar,
foreign_column_name varchar );
BEGIN
FOR r IN (SELECT c.table_schema, c.table_name, c.column_name, c.column_default, c.data_type, c.udt_name,
ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name
FROM information_schema.columns AS c
LEFT JOIN information_schema.key_column_usage AS kcu
ON c.table_name = kcu.table_name AND c.column_name = kcu.column_name
LEFT JOIN information_schema.constraint_column_usage as ccu
ON kcu.constraint_name = ccu.constraint_name
WHERE c.table_name = tableName) LOOP
-- My plpgsql
END LOOP;
RETURN;
END;
$BODY$ LANGUAGE plpgsql VOLATILE;
正如您所看到的,我通过命名列名称然后命名列类型来声明行r
。哪个不起作用,我收到以下错误消息:ERROR: syntax error at or near "(" Position: 615 Where: invalid type name "( table_schema varchar, table_name varchar, column_name varchar, column_default varchar, data_type varchar, udt_name varchar, foreign_table_name varchar, foreign_column_name varchar )"
我还尝试将varchar
更改为information_schema.sql_identifier
和information_schema.character_data
,这些是我尝试阅读的列的information_schema中的对象类型。
我是否正确地声明行和/或我是否应该使用不同的方法循环使用多个连接的select语句?
答案 0 :(得分:2)
如果使用记录
,也许很简单DECLARE
r record;
BEGIN
FOR r IN select * from information_schema.columns
LOOP
...
END LOOP;