SQLite应用之路---删除列
SQLite,并不支持列的删除,所以我们只能“曲线救国”。
1.思路
(1)我们通过临时表来实现,首先我们创建和目标表结构的临时表(除去要删除的字段);
(2)把目标表中的数据放入临时表;
(3)然后我们将目标表删除(drop),并重新创建(除去要删除的字段,和原来的目标表结构一样);
(4)我们把临时表中的数据放回目标表,并删除临时表。
2.例子
目标表target_table(id int primary key,nametext,sex text,age int);
//其中sex字段是要被删除的字段
步骤(1):创建临时表
create temp table temp_target_table(id int primary key,name text,age int);
步骤(2):保存数据
insert into temp_target_table(id,name,age) select id,name,age from target_table
步骤(3)删除目标表,并重创建
drop table target_table;
create table target_table(id int primarykey,name text,age int);
步骤(4)将数据放回目标表,并删除临时表
insert into target_table(id,name,age) select id,name,age from temp_target_table;
drop table temp_target_table;
3.来自官网
SQLite,关于删除字段这一点,这里我放上SQLite官网上的解释:
(我是一个链接)
SQLite has limited ALTERTABLE support that you can use to add a column to the end of atable or to change the name of a table. If you want to make more complexchanges in the structure of a table, you will have to recreate the table. Youcan save existing data to a temporary table, drop the old table, create the newtable, then copy the data back in from the temporary table.
For example,suppose you have a table named "t1" with columns names "a","b", and "c" and that you want to delete column"c" from this table. The following steps illustrate how this could bedone:
BEGIN TRANSACTION;
CREATE TEMPORARY TABLE t1_backup(a,b);
INSERT INTO t1_backup SELECT a,b FROM t1;
DROP TABLE t1;
CREATE TABLE t1(a,b);
INSERT INTO t1 SELECT a,b FROM t1_backup;
DROP TABLE t1_backup;
COMMIT;