我对 SQLite 3 还很陌生,现在我必须向现有的表中添加一列。我开始这样做:
ALTER TABLE thetable ADD COLUMN category;
。
当然,我忘记指定该列的类型。我想做的第一件事就是删除该列,然后重新添加它。然而,SQLite 似乎没有一个简单的方法来执行此操作,我必须备份表并在没有列的情况下重新创建它。
这看起来很混乱,我想知道是否有一种修改/添加列类型的方法。我想是这样,但是我的搜索没有结果,作为 SQLite 的新手,我想这是因为我的措辞在查询中不正确。
如果您更喜欢 GUI,SQLite 的数据库浏览器 只需点击几下即可完成此操作。
SQLite 的数据库浏览器是开源且免费的。对于 Linux,可以从存储库中获取它。
有一个更简单的方法:
ALTER TABLE your_main_table
ADD COLUMN new_column_name new_column_data_type
UPDATE your_main_table
SET new_column_name = CAST(old_column_name as new_data_type_you_want)
我在本地机器上尝试过,它有效
可以通过重新创建表格来实现。它对我有用,请按照以下步骤操作:
在工作线程中执行上述所有步骤以减少 uithread 上的负载
可以通过转储、编辑和重新导入表来实现。
此脚本将为您完成此操作(根据您的需要调整脚本开头的值):
#!/bin/bash
DB=/tmp/synapse/homeserver.db
TABLE="public_room_list_stream"
FIELD=visibility
OLD="BOOLEAN NOT NULL"
NEW="INTEGER NOT NULL"
TMP=/tmp/sqlite_$TABLE.sql
echo "### create dump"
echo ".dump '$TABLE'" | sqlite3 "$DB" >$TMP
echo "### editing the create statement"
sed -i "s|$FIELD $OLD|$FIELD $NEW|g" $TMP
read -rsp $'Press any key to continue deleting and recreating the table $TABLE ...\n' -n1 key
echo "### rename the original to '$TABLE"_backup"'"
sqlite3 "$DB" "PRAGMA busy_timeout=20000; ALTER TABLE '$TABLE' RENAME TO '$TABLE"_backup"'"
echo "### delete the old indexes"
for idx in $(echo "SELECT name FROM sqlite_master WHERE type == 'index' AND tbl_name LIKE '$TABLE""%';" | sqlite3 $DB); do
echo "DROP INDEX '$idx';" | sqlite3 $DB
done
echo "### reinserting the edited table"
cat $TMP | sqlite3 $DB
我已经通过临时表完成了,
create temp table temp_view as select target_col from target_table
-- first store the values of the target col in the temp. table
alter table target_table drop target_table;
-- Drop the column
alter table target_table add target_table new_type;
-- Add the column with the required type, it would have NULL Values
update target_table set target_col = (select target_col from temp_view);
-- Update the values from temp. table