Postgresql

使用動態 SQL 創建索引

  • February 4, 2016

我有以下用於創建要點索引的程式碼

CREATE INDEX web_stats_project_107_properties_crosspromo_gist_idx 
   ON web_stats_project_107 USING gist (properties) 
   WHERE properties @> '"block_level_0"=>"cerber-head"'::hstore  
       AND properties @> '"block_level_1"=>"head"'::hstore 
       AND properties @> '"block_level_2"=>"cross-news"'::hstore
       AND properties ? 'block_level_5'::text
       AND (NOT (properties ? 'block_level_6'::text));

當我直接使用它時,它執行順利。

但我需要在觸發器中使用它和一些變數。問題來了。

我嘗試了兩種程式碼變體:

createIndex := 'CREATE INDEX idx_'||Fulltable_name||'_properties_crosspromo_gist 
ON public.'||Fulltable_name||' USING gist (properties) 
WHERE properties @> '"block_level_0"=>"cerber-head"'::hstore 
AND ...;

createIndex := 'CREATE INDEX idx_'||Fulltable_name||'_properties_crosspromo_gist 
ON public.'||Fulltable_name||' USING gist (properties) 
WHERE (((((properties @> '"block_level_0"=>"cerber-head"'::hstore) 
AND ...;

由於語法錯誤,我什至無法將其應用於 DB

錯誤:“=>”處或附近的語法錯誤 LINE 32: …perties) WHERE (((((properties @> ‘“block_level_0”=>“cerber-…

要麼

錯誤:“CREATE”第 32 行或附近的語法錯誤:

createIndex := ‘createIndex := ‘CREATE INDEX idx…

似乎我必須用一些字元來轉義一些符號。

任何想法如何做到這一點?

createIndex := 'CREATE INDEX idx_'
   || Fulltable_name
   || '_properties_crosspr_gist ON public.'
   || Fulltable_name
   || ' 
   USING gist (properties) 
   WHERE properties @> $$"block_level_0"=>"cerber-head"$$::hstore 
     AND properties @> $$"block_level_1"=>"head"$$::hstore 
     AND properties @> $$"block_level_2"=>"cross-news"$$::hstore 
     AND properties ? $$block_level_5$$::text 
     AND NOT properties ? $$block_level_6$$::text';

引用自:https://dba.stackexchange.com/questions/126867