第2部分 資料庫SQL語言
如何擴充資料表字段?
【文章摘要】
在通信類軟體中,經常會與資料庫打交道。由于需求變化,或者是程式優化更新等原因,對資料表字段進行擴充是常有的事情。這就要求開發人員必須熟練掌握對資料表字段進行擴充的操作流程。
本文基于作者的資料庫方面的工作經驗,以實際的SQL程式為例,詳細介紹了如何對對資料表字段進行擴充,為相關的開發工作提供了參考。
【關鍵詞】
資料庫 資料表 擴充 SQL 開發
一、前言
在實際的軟體開發項目中,對資料表字段的擴充包括如下兩個方面:
第一,對原有字段值的擴充。例如,原表有一個字段“result”,表示結果,之前的取值為0和1,現在要擴充其取值範圍,添加一個結果值2。對于此類擴充,資料表的結構不用動,隻需要讓相關子產品知道有這個值的擴充即可。
第二,新增加字段。即原來表已有的字段不能滿足目前的要求,需要新增一個或幾個字段,這就涉及到資料表結構的改變。
本文主要讨論第二種情況下資料表字段擴充的流程和操作方法。本文中的所有腳本都是基于Sybase資料庫。
二、資料表字段擴充的流程
對于新增字段的情況,不能通過簡單的删除表和重建表來完成,因為在實際的軟體運作環境中,幾乎每個資料表裡面都會有很多的資料。如果不管三七二十一,将表删除了,會導緻某些重要資料的丢失,造成極為不良的影響,甚至會引起客戶的投訴。
在實際的軟體開發項目中,對資料表字段的擴充流程如圖1所示。
圖1 對資料表字段的擴充流程
三、資料表字段擴充操作示例
有一個員工資訊表,包含了工号、姓名和年齡三個字段,如下所示:
create table tb_employeeinfo
(
workid int default(0) not null, -- workid
name varchar(50) default('') not null, -- name
age int default(0) not null -- age
)
go
create unique index idx1_tb_employeeinfo on tb_employeeinfo(workid)
print 'create table tb_employeeinfo ok'
現在需要在原表的基礎之上擴充一個位址(address)字段,用于記錄員工的居住位址,該字段可以為空。
整個字段擴充的執行SQL腳本如下:
-- 第一步: 建立備份表
if exists(select * from sysobjects where name='tb_employeeinfobak')
drop table tb_employeeinfobak
create table tb_employeeinfobak
workid int default(0) not null, -- workid
name varchar(50) default('') not null, -- name
age int default(0) not null -- age
create unique index idx1_tb_employeeinfobak on tb_employeeinfobak(workid)
print 'create table tb_employeeinfobak ok'
-- 第二步: 将原表内容插入到備份表中
insert into tb_employeeinfobak(workid, name, age) select workid, name, age from tb_employeeinfo
-- 第三步: 将原表删除掉
if exists(select * from sysobjects where name='tb_employeeinfo')
drop table tb_employeeinfo
-- 第四步: 建立新表
workid int default(0) not null, -- workid
name varchar(50) default('') not null, -- name
age int default(0) not null, -- age
address varchar(100) null -- address
-- 第五步: 将備份表内容插入到新表中
insert into tb_employeeinfo(workid, name, age) select workid, name, age from tb_employeeinfobak
-- 第六步: 删除備份表
經過以上六個步驟,即實作了對資料表的字段擴充,并且原來的資料也沒有丢失。
四、總結
本文以實際的SQL腳本為例,詳細介紹了對資料表字段進行擴充的整個流程,為相關軟體開發活動的開展提供了有益的參考。