首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> DB2 資料庫 >> DB2 教學

DB2 入門百問精選(三):摘要表、暫存表、視圖、別名與序列完整語法指南

     編輯:DB2 教學

前言

本文延續「DB2 常見問題 1000 問」系列第三部分,聚焦 摘要表(MQT)、全域暫存表、視圖、別名、序列 五大物件的建立、管理與修改語法,所有範例基於 DB2 7.x,關鍵字統一小寫,適合新手速查與實戰參考。

一、摘要表——對應 Oracle 實體化視圖

1.1 建立可重新整理的摘要表

create summary table table_name as (
  select * from table_name1 where col1 = 'AAA'
) data initially deferred refresh deferred;
  • data initially deferred:建立時不填入資料
  • refresh deferred:資料透過 refresh table 手動重新整理

1.2 重新整理與修改

refresh table sum_table;          -- 重新整理
alter table sum_table ...;        -- 修改結構

二、全域暫存表——Session 級隔離、自動清理

2.1 語法結構

declare global temporary table table_name
as (fullselect) definition only
excluding identity column attributes
on commit delete rows
not logged;

關鍵字說明:

  • definition only:僅複製欄位定義,不複製資料
  • excluding identity column attributes:不複製恆等欄位屬性
  • on commit delete rows:若無 with hold 游標,Commit 時自動清空資料
  • not logged:變更不寫入交易日誌,效能最佳

2.2 實戰範例

declare global temporary table dec_bsempms
as (select * from bsempms) definition only
excluding identity column attributes
on commit delete rows
not logged;

三、視圖管理

create view view_name as select * from table_name where ...;
drop view view_name;

查詢視圖定義:select * from syscat.views 的 text 欄位。

四、別名——跨結構、跨類型的別名引用

create alias alias_name for pro_name;

pro_name 可為 TABLE、VIEW、ALIAS、NICKNAME 等,支援鏈式別名。

五、序列——自動產生唯一數值

5.1 建立序列

create sequence sequence_name
start with start_number
increment by value1
nomaxvalue
nocycle
cache maximum_number_of_sequence_values;
  • start with:初始值
  • increment by:遞增幅度
  • nomaxvalue:無上限
  • nocycle:達上限不循環
  • cache:預先配置序列值數量(效能優化)

5.2 修改序列

alter sequence sequence_name ...;

可調整參數:start with、increment、maxvalue、cycle、cache。

結語

掌握上述五大物件的 DDL 語法與關鍵選項,可覆蓋 80% 以上的日常開發與管理場景。建議收藏備查,實戰中活用 not logged 暫存表提升批次效能,善用 cache 參數減少序列鎖競爭。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved