【问题标题】:do nothing if table doesn't exist如果表不存在,什么也不做
【发布时间】:2016-10-27 20:01:47
【问题描述】:

我只想在表存在时执行查询。

如果表不存在,什么也不做。

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

我想要这个/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)  {

当表格为空时它可以工作,但是当我填满表格时应该做select * from table它会抛出error: query has no destination for result data

【问题讨论】:

  • 如果 mytable 中的数据存在,你想要什么?..
  • @VaoTsun:例如,当我单击(进入我的程序)字段 CheckMe 时,它会显示 mytable 中的所有字段。当它已满时会发生这种情况。当表为空时,我我收到一个错误(因为它是空的)。所以,我想避免这种情况。
  • 所以你想检查表是否存在然后检查表中是否有一些数据,如果有一些你想选择它?...全部在一个过程中 - 对吗?..跨度>
  • @VaoTsun:是的,就是这样!
  • 然后更新您的问题,以便其他人了解您的需求

标签: node.js postgresql


【解决方案1】:

考虑改用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);
          }
        });
      }
});

【讨论】:

  • :当表是空的,我第一次访问它只是挂起,没有错误。当表满时,它工作正常! (您错过了外部查询的});
  • :由于某种原因,它没有返回table is empty。它挂起
  • 在没有数据的情况下运行并显示您在此处看到的内容:console.log('no data',res.rows);
  • 如果我在第二个查询中运行console.log,它仍然挂起而不显示任何内容。如果我将console.log(no data 放在第一个查询中,它会返回no data [ anonymous { c: '0' } ]跨度>
  • Here 是在第一个查询中打印docs 的结果。
猜你喜欢
  • 2021-09-13
  • 2019-01-17
  • 2011-04-07
  • 2020-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多