我正在表中创建一个列:
client.query("ALTER TABLE mytable ADD theField text", function(err, result) {
现在,我想执行一个测试,所以如果该列已经存在,请不要执行该语句。
我试过了:
client.query("ALTER TABLE mytable IF NOT EXISTS ADD theField text", function(err, result) {
client.query("ALTER TABLE mytable ADD theField text IF NOT EXISTS", function(err, result) {
client.query("ALTER TABLE mytable WHERE EXISTS (SELECT 1 FROM mytable ADD theField text)", function(err, result) {
但都给出了语法错误。
答案 0 :(得分:1)
您的代码ALTER TABLE mytable IF NOT EXISTS ADD theField text
将添加列thefield
。如果你想要精确调用它theField
,你应该运行它:ALTER TABLE mytable IF NOT EXISTS ADD "theField" text
这就是为什么我检查列是否存在忽略大小写的原因:lower(blaH-BLah)
等于lower(blAh-bLAh)
,因为它使blah-bLah
值。这就是您的查询应该是:
client.query("do"+
" $$"+
"begin"+
" if (select count(*) from information_schema.columns" +
" where table_schema = 'public' " +
" and table_name = 'mytable' "+
" and lower(column_name) = lower('theField')) < 1 " +
" then "+
"ALTER TABLE mytable ADD \"theField\" text;"+
"end if;"+
"end;"+
"$$"+
";", function(err, result) {