以下每個表 ['table1', 'table2'] 都是公共模式的一部分,知道每個表可能包含多個列,其中包含名稱中的子字串 'substring' 示例讓我們看看以下內容:
Table_1 (xyz, xyz_ substring ,...some_other_columns...abc, abc_ substring )
Table_2 (xyz, xyz_ substring ,..some_other_columns ... abc, abc_ substring )
我是從一種 Python 的思維方式得出這個結論的,但基本上,由于我們需要定位的列需要滿足特定的條件,所以如何在不確切知道要設定什么的情況下執行陳述句?
我的想法是在當前表的列名上添加另一個回圈,并檢查名稱是否符合條件。然后執行查詢,但感覺離最佳狀態很遠。
DO $$
declare
t text;
tablenames TEXT ARRAY DEFAULT ARRAY['table_1', 'table_2'];
BEGIN
FOREACH t IN ARRAY tablenames
LOOP
raise notice 'table(%)', t;
-- update : for all the column that contain 'substring' in their names set a value
END LOOP;
END$$;
編輯:感謝@Stefanov.sm的回答,我完全按照您的想法,并且能夠將您的邏輯建立在只有一個陳述的基礎上:
DO $$
declare
t text;
tablenames TEXT ARRAY DEFAULT ARRAY['table_1', 'table_2'];
dynsql text;
colname text;
BEGIN
FOREACH t IN ARRAY tablenames LOOP
raise notice 'table (%)', t;
dynsql := format('update %I set', t);
for colname in select column_name from information_schema.columns where table_schema = 'public' and table_name = t
loop
if colname like '%substring%' then
dynsql := concat(dynsql,format(' %I = ....whatever expression here (Make sure to check if you should use Literal formatter %L if needed) ....,',colname,...whateverargs...));
end if;
end loop;
dynsql := concat(dynsql,';'); -- not sure if required.
raise notice 'SQL to execute (%)', dynsql;
execute dynsql;
END LOOP;
END;
$$;
uj5u.com熱心網友回復:
提取每個表的列串列,然后格式化/執行動態 SQL。就像是
DO $$
declare
t text;
tablenames text[] DEFAULT ARRAY['table_1', 'table_2'];
dynsql text;
colname text;
BEGIN
FOREACH t IN ARRAY tablenames LOOP
raise notice 'table (%)', t;
for colname in select column_name
from information_schema.columns
where table_schema = 'public' and table_name = t loop
if colname ~ '__substring$' then
dynsql := format('update %I set %I = ...expression... ...other clauses if any...', t, colname);
raise notice 'SQL to execute (%)', dynsql;
execute dynsql;
end if;
end loop;
END LOOP;
END;
$$;
這會導致過度膨脹,所以不要忘記vacuum你的桌子。如果您的表的架構不是public,則相應地編輯選擇information_schema。您可以使用pg_catalog資源來代替information_schema。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/519432.html
