且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果存在sqlite,则重命名列?

更新时间:2023-11-22 22:58:22

据我所知,没有办法按照你的要求去做.但是你可以使用

As far as I know there is no way to do what you ask. However you can use

SELECT sql FROM sqlite_master
WHERE tbl_name = 'table_name' AND type = 'table'

检查该列是否存在.但是,因为一旦我不知道重新创建表有什么问题,您就必须重命名该列.娱乐意味着数据丢失.

to check whether the column exists or not. However since you just have to rename the column once I do not know what the issue is with the recreation of the table. Recreation does NOT mean data loss.

该过程将遵循:

  1. 开始交易;
  2. ALTER TABLE table RENAME TO tmp_table;
  3. CREATE TABLE table (columnNames);
  4. INSERT INTO table(columnNames) SELECT columnNamesWrong FROM tmp_table;
  5. 删除表 tmp_table_name;
  6. COMMIT;

如果这太麻烦了,请使用工具来完成.

If this is to much fuss use a tool to do it.

关于***实践部分,***实践是正确命名您的表.由于您通常围绕字段名称构建所有查询,因此重命名列意味着破坏这些查询.我不知道您在寻找什么,但 sqlite 手册 指出:

About the best practice part, it is best practice to get your tables named properly. Since you usually build all your queries around the field names renaming columns means breaking those queries. I do not know what you are looking for but the sqlite manual states:

SQLite 支持有限的 ALTER TABLE 子集.更改表SQLite 中的命令允许用户重命名表或添加新表列到现有表.无法重命名列,删除列,或者在表中添加或删除约束.

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table.

注意什么是不可能的.