2016-06-01 3 views
2

私はすべてのテーブルの存在をチェックしたいと思います。すべてのテーブルが存在する場合は1を、1つ以上のテーブルがない場合は0を送信します。すべてのテーブルの存在を確認するには? in postgresql

select 1 from information_schema.tables tbl where tbl.table_name='graphe'; 
select 1 from information_schema.tables tbl where tbl.table_name='proprieteindicateur'; 
select 1 from information_schema.tables tbl where tbl.table_name='graphe_proprieteindicateur'; 
select 1 from information_schema.tables tbl where tbl.table_name='utilisateurs'; 
select 1 from information_schema.tables tbl where tbl.table_name='profil'; 
select 1 from information_schema.tables tbl where tbl.table_name='droit'; 
+0

いかなる理由がお役に立てば幸いですか!可能であれば、カウントを予想される回答と比較する関数を作成します。次に、結果に基づいて1または0を返します。 – Crackerman

+0

理由はありません。テーブルが存在し、1または0を返すかどうかをチェックするリクエストを1つしか受けられないようにしたいと考えています。 しかし、詳細を伝えることができますか? –

答えて

0

条件に基づいて0または1を返す関数を作成できます。例えば(私は構文をチェックするためにPostgresデータベースへのアクセスを持っていない!):

CREATE OR REPLACE FUNCTION checkTables() 
RETURNS smallint AS 
$BODY$ 
DECLARE 
cnt smallint; 
rntVal smallint; 
begin 
    SELECT count(1) 
    INTO cnt 
    FROM information_schema.tables tbl 
    where tbl.table_name IN ('graphe', 
          'proprieteindicateur', 
          'graphe_proprieteindicateur', 
          'utilisateurs', 
          'profil', 
          'droit'); 

    if(cnt == 6)then 
    rtnVal = 1 
    else 
    rtnVal = 0 
    end if; 
end; 
return rtnVal; 
$BODY$ 
LANGUAGE plpgsql VOLATILE 
+0

あああああああ、ありがとう!しかし、私はそれが言う理由を得ることができません: エラー:または "ELSE"近くの構文エラー –

+0

は、 "rtnVal = 1"の後にセミコロンがない可能性がありますか?あなたはそれを動作させるためにそれと遊ぶ必要があります。私は構文チェッカーを持っていません。 – Crackerman

+0

ハハ大丈夫です。私は今すぐsuccedように見えることはできませんが、私はそれを見つけるでしょう。 貴重なご協力ありがとうございました! –

1

これは、1つのステートメントで行うことができます。

with table_list (name) as (
    values 
    ('graphe'), 
    ('proprieteindicateur'), 
    ('graphe_proprieteindicateur'), 
    ('utilisateurs'), 
    ('profil'), 
    ('droit') 
) 
select count(*) = (select count(*) from table_list) 
from information_schema.tables it 
    join table_list l on it.table_name = l.name 
and it.table_schema = 'public'; 

すべてのテーブルが検出された場合にはtrueを返します。 、そうでない場合はfalse

0

非常にうまくいく別の解決策が見つかりましたが、それはシェルにあります。

PRESENCE_TABLE=$OK 
for table in $LISTE_TABLE 
do 
    TABLE_EXISTE=$(psql -t -w -f $FILE_SQL_VERIF_MDD --set nom=\'$table\' | tr -d " ") 
    if [ -z $TABLE_EXISTE ] 
    then 
     echo_log -e "La table $table n''existe pas en base." 
     PRESENCE_TABLE=$KO 
    fi 
done 


if [ $PRESENCE_TABLE -ne $OK ] 
then 
    echo_log -e "Il manque de(s) table(s) dans le modele de donnees, il faut relancer le script avec l'option ...." 
    fct_exit $KO 
fi 

は、それはあなたが「1」「)(数」とを交換し、テーブル名のリストで「IN」ステートメントを使用できなかった理由

関連する問題