Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

node.js - do nothing if table doesn't exist

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.

I want this /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)  {

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

If I use 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 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...