DB2 修改表列相關屬性

Hoking發表於2019-04-30

1.更改型別

 ALTER TABLE "SCHEMA"."TABLENAME" ALTER COLUMN "COL" SET DATA TYPE VARCHAR(32);  

:設定為主鍵的列不能更改型別

2.更改預設值 

ALTER TABLE "SCHEMA"."TABLENAME" ALTER COLUMN "COL" SET DEFAULT 'ABC';  

3.系統預設值

 ALTER TABLE "SCHEMA"."TABLENAME" ALTER COLUMN "COL" SET DEFAULT; --設定預設值  
 ALTER TABLE "SCHEMA"."TABLENAME" ALTER COLUMN "COL" DROP DEFAULT; --刪除預設值  

4.更改是否允許空值

 ALTER TABLE "SCHEMA"."TABLENAME" ALTER COLUMN "COL" SET NOT NULL;  
 ALTER TABLE "SCHEMA"."TABLENAME" ALTER COLUMN "COL" DROP NOT NULL;

5.建立、刪除唯一約束

ALTER TABLE "SCHEMA"."TABLENAME" ADD unique("COL")
ALTER TABLE "SCHEMA"."TABLENAME" DROP unique "COL"

6.建立主鍵約束

ALTER TABLE "SCHEMA"."TABLENAME" ADD PRIMARY key ("COL1","COL2")
ALTER TABLE "SCHEMA"."TABLENAME" DROP PRIMARY key

☆注:
1、更改列型別,是否允許空值後,需要執行REORG TABLE "TABLENAME";  
2、更改預設值後,通常需要執行UPDATE "SCHEMA"."TABLENAME" SET "COL" = DEFAULT WHERE "COL" IS NULL; 

相關文章