postgresql 在某個記錄中查詢滿足條件的欄位 findfield
最近,在一個Insert SQL時報欄位長度不夠,但又沒指出哪個欄位,表的欄位數很多,看了好久都沒找出是哪個欄位,心想有什麼辦法能按指定條件過濾當前記錄的所有欄位不就能找出我想要的欄位嗎?昨天終於用hstore寫出了一個滿足需求的函式,特記錄如下,備查。
--usage:
-- select * from findfield('select * from sales_orders where id=1000','length(value)>=50 and value ilike ''%car%''');
-- Function: public.findfield(text, text); -- DROP FUNCTION public.findfield(text, text);
CREATE OR REPLACE FUNCTION public.findfield( IN sql text, IN wh text, OUT fldname text, OUT fldvalue text ) RETURNS SETOF RECORD AS $BODY$ DECLARE sql0 text; rec record; BEGIN if sql='' then sql := 'select 1 as v'; end if; if wh='' then wh := 'false'; end if; sql0 := 'with h as (' || sql ||' ) '; sql0 := sql0 || ',h1 as (select hstore(h) v from h)'; sql0 := sql0 || ',h2 as (select a.key as name,a.value from h1,each(h1.v) a)'; sql0 := sql0 || 'select * from h2 where ' || wh || ';'; for rec in EXECUTE sql0 loop fldname := rec.name; fldvalue := rec.value; return next; end loop; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100; ALTER FUNCTION public.findfield(text, text) OWNER TO root;