Sql代碼
- --建立了一個産品資訊表
- create table productinfo(
- productId varchar2(20) unique,
- productName varchar2(10) not null,
- productPrice varchar2(10) primary key,
- productAddress varchar2(10) );
- --練習使用sql修改限制和字段大小
- alter table productinfo modify
- productAddress varchar2(20) not null;
- --練習使用sql删除,修改,新增表裡面的限制
- alter table productinfo
- --drop constraint sys_c009964;(删除的是productPrice為主鍵的限制)
- --modify productPrice constraint product_price_not not null;(給productPrice增加非空的限制)
- --add constraint productin_address_check check(length(productAddress)>5);(給位址增加check限制)
- add constraint productinfo_pk primary key(productId);--增加productid為主鍵的限制
- --檢視所有的限制名字,限制的狀态(是否啟用) ,限制的類型,限制是建立在哪個列上面的
- select c.constraint_name, c.status, c.constraint_type,n.COLUMN_NAME
- from user_constr select * from productinfo_bak ;
- aints c, user_cons_columns n
- where c.CONSTRAINT_NAME = n.CONSTRAINT_NAME and c.TABLE_NAME= 'PRODUCTINFO';
Sql代碼
- --修改字段的長度
- alter table productinfo_bak
- modify productName varchar2(20);
- --使用匿名程式塊,在裡面使用loop循環給表出入9條資料
- declare
- begin
- for i in 1 .. 9 loop
- insert into productinfo
- (productid, productname, productprice, productaddress)
- values
- ('GD01001000'||i,'LG手機'||i,'手機價格'||i,'西安市南山區位址'||i);
- commit;
- end loop;
- dbms_output.put_line('總共插入了'||sql%rowcount||'條記錄.');
- end;
- --使用子查詢建立表productinfo_bak
- create table productinfo_bak as select * from productinfo where 1<>1;
- --使用merge語句給表productinfo_bak裡面插入一條p.productid ='GD010010001'的記錄
- merge into productinfo_bak p_bak
- using productinfo p
- on (p_bak.productId = p.productId)
- when not matched then
- insert
- (p_bak.productid,
- p_bak.productname,
- p_bak.productprice,
- p_bak.productaddress)
- values
- (p.productid, p.productname, p.productprice, p.productaddress) where p.productid = 'GD010010001';
- --建立觸發器,行級觸發器(for each row),在更新productinfo表的時候觸發事件
- create or replace trigger tr_auto_update_productinfo
- after update on productinfo for each row
- begin
- update productinfo_bak p_bak set
- p_bak.productid = :new.productid, p_bak.productname = :new.productname,
- p_bak.productprice = :new.productprice, p_bak.productaddress = :new.productaddress
- where p_bak.productid = :old.productid;
- dbms_output.put_line('你在更新産品資訊的時候,觸發器自動更新了産品備份表裡面的資訊!');
- exception
- when others then
- dbms_output.put_line(sqlcode ||' ,' ||sqlerrm);
- end;
- select * from productinfo;
- select * from productinfo_bak;
- update productinfo p set p.productname = '金鵬1' where p.productid = 'GD010010001';
- select * from productinfo_bak;
- --在本例子中我犯了一個緻命的錯誤就是在觸發器的定義當中使用了事物控制語句