【问题标题】:add column only if table not exists仅当表不存在时才添加列
【发布时间】:2016-10-19 03:12:01
【问题描述】:

我正在表格中创建一列:

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

但都给出语法错误。

【问题讨论】:

    标签: sql node.js postgresql


    【解决方案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)  {
    

    【讨论】:

    • 什么是myschema
    • 你的表所在的模式名称
    • 如果您没有在任何地方指定它 - 应该是公开的
    • :我正在接收:There was an error : { error: missing "THEN" at end of SQL expression。我上传了here。注意,我在外面使用了' ',以便使用theField。我省略了lower(..)
    • 如果要检查列是否存在,则不能省略列部分。您也不能将"' 用于文本值,dbl 配额用于对象名称。在这种情况下,theField 等不是名称 - 它是 where 子句的一部分
    猜你喜欢
    • 2023-03-19
    • 2012-04-11
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2019-03-05
    相关资源
    最近更新 更多