我有一张表newb
看起来像这样:
tablename | columnname
-----------------------
walls | id
floors | rowid
首先我创建一个数组:
CREATE TABLE finalsb
(
tabnam newb ARRAY
);
然后我将表中的数据放入数组中:
INSERT INTO finalsb VALUES(ARRAY(SELECT newb FROM newb));
以下语句显示表newb中的'id'
:
SELECT tabnam[1].columnname FROM finalsb;
我想做类似的事情:
Declare colvar varchar,tabvar varchar
colvar = Select tabnam[1].columnname from finalsb;
tabvar = Select tabnam[1].tablename from finalsb;
我的主要目标是:
SELECT * FROM tabvar WHERE colvar = "somevalue";
有谁能告诉我如何将SELECT
语句声明为变量?
答案 0 :(得分:0)
您必须使用select ... into variable
构造:
do $$
declare
colvar varchar;
tabvar varchar;
begin
select tabnam[1].columnname into colvar from finalsb;
select tabnam[1].tablename into tabvar from finalsb;
raise notice 'tabvar: %, colvar: %', tabvar, colvar;
end
$$;
要运行动态sql plpgsql,需要execute
:
execute format('SELECT * FROM %s WHERE %s = "somevalue"', quote_ident(tabvar), quote_ident(colvar));
例如以函数的形式返回语句:
return query execute format('SELECT * FROM %s WHERE %s = "somevalue"', quote_ident(tabvar), quote_ident(colvar));
推荐阅读:
https://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-