SQLite应用之路---删除字段

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;

 

 

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值