如果表不存在,则不执行任何操作 [英] do nothing if table doesn't exist

查看:129
本文介绍了如果表不存在,则不执行任何操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to execute a query only if the table exists.

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

If the table doesn't exist do nothing.

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

Hence, I want to check if table exists then check if there is some data in the table and if there are some ,select them.

我要此 /client.query( SELECT * FROM mytable,function(err,res){

因此,我尝试过类似的事情:

So , I tried something like :

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)  {

我不确定使用不要做什么,现在我收到错误: NOTHING或附近的语法错误

I am not sure about the use of DO NOTHING , and right now I am receiving error: syntax error at or near "NOTHING"

如果我不使用:

 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 它引发错误:查询没有结果数据的目的地

Ιt works when the table is empty ,but when I fill the table where it should do select * from table it throws error: query has no destination for result data

推荐答案

concider使用回调,类似这样:

concider using callback instead, smth like this:

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);
          }
        });
      }
});

这篇关于如果表不存在,则不执行任何操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆