2016-06-25 97 views
-2

我只想在表存在的情况下执行查询。如果表不存在

如果表不存在,请不要执行任何操作。

因此,我想检查表是否存在,然后检查表中是否有一些数据,如果有,请选择它们。

我想这/client.query("SELECT * FROM mytable", function(err,res) {

所以,我想是这样的:

client.query("do"+ 
        " $$"+ 
        "begin"+ 
        " if (select count(*) from information_schema.columns" + 
        "  where table_schema = 'public' " + 
        " and table_name = 'mytable')"+ 
        " then "+ 
        "DO NOTHING;"+ 
        "else "+ 
        "SELECT * FROM mytable;" + 
        "end if;"+ 
        "end;"+ 
        "$$"+ 
        ";", function(err, res) { 

我不知道有关使用DO NOTHING,而现在我收到error: syntax error at or near "NOTHING"

如果我使用NOT:

client.query("do"+ 
         " $$"+ 
         "begin"+ 
         " if NOT (select count(*) = 0 from information_schema.columns" + 
         "  where table_schema = 'public' " + 
         " and table_name = 'mytable')"+ 
         " then "+ 
         "SELECT * FROM mytable;" + 
         "end if;"+ 
         "end;"+ 
         "$$"+ 
         ";", function(err, res) { 

Ιt工作时,表是空的,但是当我填写表中应做到select * from table它抛出error: query has no destination for result data

+1

你想从数据什么 –

+0

@VaoTsun:当我点击(在我的程序上)“CheckMe”字段时,它会显示mytable中的所有字段。当它满了时会发生这种情况。当表为空时,我我得到一个错误(因为它是空的)。所以,我想避免这个。 – George

+0

所以你想检查表是否存在,然后检查表中是否有一些数据,如果有一些你想选择它?..所有在一个过程 - 对吗? –

回答

0

海外商品会有用callback代替,水木清华这样的:

client.query("select count(*) c from information_schema.columns" + 
    "  where table_schema = 'public' " + 
    " and table_name = 'mytable'", function(err, res) { 
     if (parseInt(res.rows[0].c) > 0) { 
     client.query("select * from PUBLIC.mytable", function(err1, res1) { 
      if (res1.rows.length == 0) { 
      console.log('table is empty'); 
      } else{ 
      console.log(res1.rows[0].some_field); 
      } 
     }); 
     } 
}); 
+0

:当表格是空的,我第一次访问时,它只是挂起,没有错误。当表格满了,它工作正常! (你错过了一个'});'为外部查询) – George

+0

它现在更新 –

+0

:由于某种原因它不会返回'表是空的'。它挂起 – George