我知道这是一个有点牵强的问题,但它是否可以以任何方式做到?
select cc.schema,
(select exists(select *
from (select cc.schema).helpers cs
where cs.chain_id=cc.id)
) as hasHelpers
from customer.chain cc
where cc.id=$1
我要做的是将cc.schema
转换为exists语句中的模式名称!这可能吗?如何?
如果我尝试运行上述语句,我会收到错误:
FROM中的子查询必须有一个别名....来自(选择 cc ...
答案 0 :(得分:0)
您需要动态SQL 。我建议一个功能:
CREATE OR REPLACE FUNCTION f_chk_schemas(_id integer)
RETURNS TABLE (schema text, schema_exists bool, has_helpers bool) AS
$func$
BEGIN
FOR schema, schema_exists, has_helpers IN
SELECT cc.schema, to_regclass(quote_ident(cc.schema) || '.helpers') IS NOT NULL
FROM customer.chain cc
WHERE cc.id = $1
LOOP
IF schema_exists THEN
EXECUTE format('SELECT EXISTS (SELECT 1 FROM %I.helpers WHERE id = $1)', schema)
USING $1
INTO has_helpers;
END IF;
RETURN NEXT;
END LOOP;
END
$func$ LANGUAGE plpgsql;
相关: