ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

前端 未结 14 1876
青春惊慌失措
青春惊慌失措 2020-11-28 08:45

We\'ve recently had the need to add columns to a few of our existing SQLite database tables. This can be done with ALTER TABLE ADD COLUMN. Of course, if the table has alre

14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 09:43

    One workaround is to just create the columns and catch the exception/error that arise if the column already exist. When adding multiple columns, add them in separate ALTER TABLE statements so that one duplicate does not prevent the others from being created.

    With sqlite-net, we did something like this. It's not perfect, since we can't distinguish duplicate sqlite errors from other sqlite errors.

    Dictionary columnNameToAddColumnSql = new Dictionary
    {
        {
            "Column1",
            "ALTER TABLE MyTable ADD COLUMN Column1 INTEGER"
        },
        {
            "Column2",
            "ALTER TABLE MyTable ADD COLUMN Column2 TEXT"
        }
    };
    
    foreach (var pair in columnNameToAddColumnSql)
    {
        string columnName = pair.Key;
        string sql = pair.Value;
    
        try
        {
            this.DB.ExecuteNonQuery(sql);
        }
        catch (System.Data.SQLite.SQLiteException e)
        {
            _log.Warn(e, string.Format("Failed to create column [{0}]. Most likely it already exists, which is fine.", columnName));
        }
    }
    

提交回复
热议问题