1. 問題提出
有人問,在sqlite中怎麼用sql語句得到一個表的列定義語句。第一反應,可能就是用.schema <tablename>
可是這是sqlite的shell指令行。
使用代碼,好像得不到結果。
幸好,sqlite它有比較特殊的系統表:
sqlite_master
sqlite_temp_master
這兩張系統表的表結構完全相同,如下所示:
sqlite> .schema sqlite_master
CREATE TABLE sqlite_master (
type text,
name text,
tbl_name text,
rootpage integer,
sql text
);
sqlite> .schema sqlite_temp_master
CREATE TEMP TABLE sqlite_temp_master (
type text,
name text,
tbl_name text,
rootpage integer,
sql text
);
2. 執行個體說明
我們通過執行個體來說明,看看.schema相當于什麼樣的sql語句執行結果:
sqlite> create table t(id int);
sqlite> create temporary table t(id int, col2 varchar(32));
sqlite> insert into t values(1);
Error: table t has 2 columns but 1 values were supplied
sqlite> drop table t;
sqlite> .tables
t
sqlite> insert into t values(1);
sqlite> create temporary table t(id int, col2 varchar(32));
sqlite> insert into t values(2, 'wang');
sqlite> .schema t
CREATE TABLE t(id int);
CREATE TABLE t(id int, col2 varchar(32));
sqlite> select sql from sqlite_master where tbl_name='t';
CREATE TABLE t(id int)
sqlite> select sql from sqlite_temp_master where tbl_name='t';
CREATE TABLE t(id int, col2 varchar(32))
sqlite> select sql from sqlite_master where tbl_name='t' and type='table' union all select sql from
sqlite_temp_master where tbl_name='t' and type='table';
CREATE TABLE t(id int)
CREATE TABLE t(id int, col2 varchar(32))
sqlite>
我們看到,建立了兩個表,都叫t, 一個是臨時表,一個是非臨時的。
建立完以後,在插入資料時,它優先認可臨時表。
當我們運作.schema t時,會把兩張表都列出來。
然後通過查詢sqlite_master中的sql字段可以得到非臨時表的建表資訊,sqlite_temp_master中的sql字段能得到臨時表的資訊。兩者的union就會得到所有表的資訊。
是以:
.schema <t>
等價于:
select sql from sqlite_master where tbl_name='<t>' and type='table' union all select sql from
sqlite_temp_master where tbl_name='<t>' and type='table';
值得一提的是,當type='index'時,還可以得到index的相關建立語句,不再綴述。