[英]Create indexes for tables with prefix in PostgreSQL
我正在嘗試實現一種為 Postgresql 中的多個表創建多個索引的方法。
現在,我寫了這樣的東西
do $$
declare temprow record;
declare idx_name character varying(200);
begin
for temprow in
select table_name from information_schema.tables where table_schema = 'public' and table_name like 'prefix%' order by table_name
loop
idx_name := 'index_name_prefix_' || temprow.table_name || '_idx';
create index idx_name ON temprow.table_name (column1 asc, column2 desc);
end loop;
end$$;
似乎這應該工作,但它沒有錯誤
ERROR: schema "temprow" does not exist
我想我會每周安排一次這個 sql,因為這是我任務的正確方法
你能幫我找出這個 SQL 中的錯誤,還是建議一種更好的方法來為多個表創建索引?
在 temprow.table_name 上create index idx_name ON temprow.table_name
的地方,表名必須是真實表,而不是帶有包含表名的字符串的變量,或任何其他動態/間接引用表名的間接方式。
temprow.table_name
的地方,語法需要schema.table
temprow
中的表table_name
上創建索引您正在尋找的是動態 SQL ; 也就是將 SQL 作為字符串寫入,然后單獨執行該字符串的代碼。
DO $do$
DECLARE
temprow RECORD;
sql_stmt CHARACTER VARYING(1024);
BEGIN
FOR temprow IN
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_name like 'prefix%' ORDER BY table_name
LOOP
sql_stmt := FORMAT(
'create index index_name_prefix_%s_idx ON %s (column1 asc, column2 desc);',
temprow.table_name,
temprow.table_name
);
EXECUTE(sql_stmt);
END LOOP;
END $do$;
工作示例:
不過要小心使用這種模式。
看看如果有人試圖通過濫用引用的表名來破解你會發生什么......
CREATE TABLE "prefix_z ON test(id); drop table prefix_test; --" (id INT);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.