積跬步,聚小流------oracle快捷添加測試數據
來源:程序員人生 發布時間:2015-02-09 08:39:10 閱讀次數:3000次
前1陣子在實行中發現問題,需要當時進行修改,而由于數據庫中數據是真實數據,不能進行修改,否則會出大紕漏吧,因而添加測試數據來方便修改,而單個添加效力太低下了,所以解決的辦法就是以真實的數據為模板增加新方便刪除的數據便可,就像將2014年的數據復制1份只將年份進行修改,刪除的時候講這個不存在的年份數據刪除便可。
相信大家很容易會想到這個方法,也很容易做出答案,舉個例子:

看這個表,由于主鍵中都是以當年年份開頭的,同時年度也是當年年份,這樣我們就能夠進行添加修改:
假使說這個表格存在以下列:
btfid、production、code、retrieveid、location、tobaccostation、plantvillage、cooperation、tobaccotechnician、eastlong、eastlat、southlong、southlat、westlong、westlat、northlong、northlat、amsl、totalarea
那樣我們可以可以這樣寫:
insert into
arc_basictobaccofield
select '2016' || substr(btfid, 5),
'2016',
code,
retrieveid,
location,
tobaccostation,
plantvillage,
cooperation,
tobaccotechnician,
eastlong,
eastlat,
southlong,
southlat,
westlong,
westlat,
northlong,
northlat,
amsl,
totalarea
from arc_basictobaccofield
where tobaccostation = '37030405C'
and productionyear = 2015
然后在刪除的時候只需要將年份為2016的全部刪除便可,但是這里還存在1個問題,實際上表的屬性可能不單單只有這么點列,事實上,就算只有這幾列,也遠遠大于我們需要修改的兩列數據了,我們是否是可以有更好的辦法來解決它呢?
答案是肯定的,這樣我們倒過來思考下,我們只需要修改兩列而已,那我們就把所有數據取出來,將這兩列數據修改以后進行插入不就能夠了么,我們來寫下看:
首先我們來創建1個臨時表:
create table arc_basictobaccofield1 as
select * from arc_basictobaccofield where tobaccostation='37030405C' and productionyear=2015
然后我們將需要修改的列進行修改:
update arc_basictobaccofield1 set productionyear=2015
update arc_basictobaccofield1 set btfid ='2015'||substr(btfid,5)
這時候候將修改后的數據導入我們需要導入的表中:
insert into arc_basictobaccofield select * from arc_basictobaccofield1
最后這1步還是很關鍵的,千萬不能忘掉:檢查導入數據,然后刪除臨時表
drop table arc_basictobaccofield1
這樣再來看,是否是不需要估計真實表究竟有多少列了呢,可見許多時候換個思考方式還是很有效力的

生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈