各位好,请教个 SQL 查询问题
场景: 动态传过来一个表名,一个 value 值(用来在 a 字段或 b 字段中检索),所有表都有 a 字段或者 b 字段,我需要判断 当前传过来的表是否有 a 或者 b,然后拼接查询条件,语句应该怎么写,PG 库
有没有合适的函数之类的,谢谢。
场景: 动态传过来一个表名,一个 value 值(用来在 a 字段或 b 字段中检索),所有表都有 a 字段或者 b 字段,我需要判断 当前传过来的表是否有 a 或者 b,然后拼接查询条件,语句应该怎么写,PG 库
有没有合适的函数之类的,谢谢。
是滴吗?
如 a 存在,返回需要的列,否则为空表格。
我这儿直接 select *了,要是根据表结构选对应查询字段我估计还得跟 where 里那样弄个子查询,分成两条 sql 就好写多了
create or replace FUNCTION f(tb text, val1 integer)
returns TABLE
(
val int
)
as
$body$
BEGIN
IF EXISTS(SELECT a.attname
from pg_class c,
pg_attribute a,
pg_type t
where c.relname = tb
and a.attnum > 0
and a.attrelid = c.oid
and a.atttypid = t.oid
and a.attname = ‘a’) THEN
return query execute ‘select a from ‘ || tb || ‘ where a = ‘ || val1;
ELSIF EXISTS(SELECT a.attname
from pg_class c,
pg_attribute a,
pg_type t
where c.relname = tb
and a.attnum > 0
and a.attrelid = c.oid
and a.atttypid = t.oid
and a.attname = ‘b’) THEN
return query execute ‘select b from ‘ || tb || ‘ where b = ‘ || val1;
END IF;
END;
$body$
language plpgsql;
lz 可以改得简洁一点
上还有用函数的方案,使用更方便,但我对这个不熟悉。