我只想在表存在的情况下执行查询。
如果表不存在则无效。
因此,我想检查表是否存在,然后检查表中是否有一些数据,如果有,请选择它们。
我想要/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
答案 0 :(得分:0)
使用callback代替,像这样smth:
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);
}
});
}
});