2013-11-04 67 views
0

我正在寫一個函數來爲給定的表計數創建表。創建一個特定的表之前,我想檢查表是否已經存在:PL/pgSQL函數不能正常工作

create or replace function test (numoftables int) returns void as $$ 
    declare 
    i integer; 
    begin 
    i:=0; 
    while i< numoftables loop 
     if not exists (select * from table$i$) -- check if table exists 
     then 
      create table table$i$(
       column1 int, 
       column2 int, 
       column1 text, 
       column2 text, 
       column3 text); 
     end if; 
    end loop; 
end; 

$$ 
language 'plpgsql'; 

當我運行這段代碼是給了我一個錯誤。

ERROR: relation "table$i$" does not exist 
LINE 1: SELECT not exists (select * from table$i$) 

誰能告訴我怎樣才能改變這種代碼都正常工作。

+2

語言名是一個普通的SQL標識,這意味着你不應該把它變成單引號。請改用'language plpgsql'。將來可能會刪除對單引號語言名稱的支持。順便說一句:爲什麼你不使用'CREATE TABLE IF NOT EXISTS ...'? –

回答

1
  • 你不能像這樣檢查表的存在。使用pg_class系統表檢查表是否存在
  • 你要增加你的我函數內部,或者你會無限循環

create or replace function test (numoftables int) returns void as $$ 
    declare 
    i integer; 
    begin 
    i:=0; 
    while i< numoftables loop 
     if not exists (select * from pg_class where relname = 'table' || i::text) 
     then 
      execute ' 
      create table table' || i::text || '(
       column1 int, 
       column2 int, 
       column3 text, 
       column4 text, 
       column5 text); 
      '; 
     end if; 
     i := i + 1; 
    end loop; 
end; 

$$ 
language 'plpgsql'; 

我已經試過沒有改變你的邏輯結束或語法很多,所以它仍然是你的功能。

sql fiddle demo

+0

它的作品,很棒! – Sameera