DB2 向表中寫資料的幾種方法

來源:互聯網
上載者:User

常用的向表中添加資料的方法如下:
 1、insert into table values(...)
 根據表指定的列,寫入相應的資料,若只給出表名,則表示按照列順序添加資料。
 添加單條資料的寫法:insert into table(col1,col2) values(value1,value2)
 添加多條資料的寫法:insert into table(col1,col2) values(value1,value2),(value3,value4),...
 
2、insert into table select ...
 這種寫法表示添加的資料來自於一個基於一個或者多個表或試圖查詢,該查詢可以進行排序分組等操作。
 如,
 db2 => create table empk(empno char(6),ename varchar(15),salary decimal(9,2))
 DB20000I  SQL 命令成功完成。
 取薪水最高的三位員工:
 db2 => insert into empk select empno,lastname,salary from employee order by salary desc fetch first 3 rows only
 DB20000I  SQL 命令成功完成。
 db2 => select *from empk
 EMPNO  ENAME          SALARY
 ------ --------------- -----------
 000010 HAAS              152750.00
 000030 KWAN              98250.00
 000070 PULASKI            96170.00
  3 條記錄已選擇。
 
3、複製表結構和資料
 我們也可以在建立表的時候,複製表結構,再使用這種方法添加資料。
 create table emp_test like employee
 insert into emp_test select * from employee where salary > 80000.00
 
也可以在複製表結構的同時,複製資料。
 create table emp_test as (select * from employee where salary > 80000.00)
 data initially deferred refresh immediate | deferred
 建立完表之後,需要重新整理一下:
 db2 => refresh table emp_test
 DB20000I  SQL 命令成功完成。
 否則將會報錯:SQL0668N  不允許對錶 "LENOVO.EMP_TEST" 執行操作,原因碼為 "1"。  SQLSTATE=57016
 
如果只是想複製表結構,不需要複製資料,可以如下建立表:
 create table emp_tt as (select empno,job,salary from employee) definition only --★
 或者
 create table emp_tt as (select empno,job,salary from employee) with no data --★
 db2 => describe table emp_tt
                                資料類型                      列
 列名                            模式      資料類型名稱      長    小數位      NULL
 ------------------------------- --------- ------------------- ---------- ----- ------
 EMPNO                          SYSIBM    CHARACTER                    6    0 否
 JOB                            SYSIBM    CHARACTER                    8    0 是
 SALARY                          SYSIBM    DECIMAL                      9    2 是
  3 條記錄已選擇。
 
db2 => select count(*) from emp_tt
 1
 -----------
          0
  1 條記錄已選擇。
 
4、Merge into語句
 merge into語句用於將一個表中的資料合併到另一個表中,當資料已經存在時,我們可以不處理或者更新之;
 具體,請參照:DB2 Merge Into語句的使用 。

 --the end--

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.