修改sqlite3中的列类型

问题描述 投票:0回答:6

我对 SQLite 3 还很陌生,现在我必须向现有的表中添加一列。我开始这样做:

ALTER TABLE thetable ADD COLUMN category;

当然,我忘记指定该列的类型。我想做的第一件事就是删除该列,然后重新添加它。然而,SQLite 似乎没有一个简单的方法来执行此操作,我必须备份表并在没有列的情况下重新创建它。

这看起来很混乱,我想知道是否有一种修改/添加列类型的方法。我想是这样,但是我的搜索没有结果,作为 SQLite 的新手,我想这是因为我的措辞在查询中不正确。

sqlite alter-table
6个回答
57
投票

SQLite 不支持删除或修改列,显然。但请记住,SQLite 中的列数据类型也不是严格的

另请参阅:


32
投票

如果您更喜欢 GUI,SQLite 的数据库浏览器 只需点击几下即可完成此操作。

  1. “文件”-“打开数据库”
  2. 在“数据库结构”选项卡中,单击表内容(不是表名称),然后单击“编辑”菜单,“修改表”,现在您可以通过下拉菜单更改任何列的数据类型。我将“文本”字段更改为“数字”,以便检索数字范围内的数据。

SQLite 的数据库浏览器是开源且免费的。对于 Linux,可以从存储库中获取它。


14
投票

有一个更简单的方法:

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)

我在本地机器上尝试过,它有效


6
投票

可以通过重新创建表格来实现。它对我有用,请按照以下步骤操作:

  1. 使用 as select * from your table 创建临时表
  2. 删除表,使用修改列类型创建表
  3. 现在将临时表中的记录插入到新创建的表中
  4. 删除临时表

在工作线程中执行上述所有步骤以减少 uithread 上的负载


0
投票

可以通过转储、编辑和重新导入表来实现。

此脚本将为您完成此操作(根据您的需要调整脚本开头的值):

#!/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

0
投票

我已经通过临时表完成了,

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
© www.soinside.com 2019 - 2024. All rights reserved.