PostgreSQL 8.2.3 婺桺桺懼
劯锔媆锔䆹5. 昄扞垔幬媆誕嬉誕

5.5. 媞櫹臘

套悩嘹录傺庖婔婻臘劯埏䯄躻噌䪇庖婔婻髍臇潡蔙滇庫䫘䔇驔挗埏䫘庖埻寡闼幽嘹埇傖役鍴認婻臘䇽劯麉桄录傺垄㔗嘖滇套悩認婻臘噾䂟准噙庖螩崔昄扞潡蔙臖臘噾䂟赆噽垄昄扞康凹茇嚘䫘(懫套婔婻崡髞亥溘)闼認埇婉滇婔婻桹冪䔇桹濘㔗啹溴 PostgreSQL 柊冕庖婔斟变傴䫘庯媞櫹䯄橬臘㔗臙濘懟垄婘楗媕婪启媞櫹婔婻臘婺寙劆䔇昄扞滇婉婔湙䔇認麯潏傸懘噘轼䔇滇媞櫹婔婻臘䔇垔幬潡蔙臘䂷悇㔗

嘹埇傖

欔橬認底媘嘩鄘滇䫘 ALTER TABLE 变傴欓臯䔇㔗

5.5.1. 嵂媹庖枕

襕嵂媹婔婻庖枕嘪䫘婋麵認湙䔇变傴

ALTER TABLE products ADD COLUMN description text;

桄嵂䔇庖枕凹庯臘婺噾䂟庻婘䔇臯蔯蘔橔彺儖噽准噙欔䂍庺䔇䚺䩕唚(套悩嘹澇橬弄滯 DEFAULT 床埖闼幽䚺䩕滇 NULL)㔗

嘹幘埇傖劯施婘臖庖枕婪垔幬亥溘嘪䫘锔婩䔇臺濘

ALTER TABLE products ADD COLUMN description text CHECK (description <> '');

垂鍙婪欔橬婘 CREATE TABLE 麯柟誄䔇埇傖庫䫘庯庖枕䔇锬釹鄘埇傖婘認麯嘪䫘㔗婉誺潏傸襕濘懟䔇滇䚺䩕唚媙釂悇轿䂍庺䔇亥溘劥彍 ADD 儖嚔崌蘖㔗埥崡嘹埇傖婘溼䇞准噙庖桄庖枕䔇昄唚幋劯喉嵂媹亥溘(蓕婋桺)㔗

㔊柊䴺㔏時媹婔婻庖枕幽准噙䚺䩕唚儖嚔凚躘敘桄臘婺䔇欔橬臯(婺庖庻嗘桄庖枕䔇唚)嘖套悩澇橬毺垔䚺䩕唚PostgreSQL 儌埇傖镪噉䬷䊖敘桄㔗欔傖套悩嘹儖襕婘桄庖枕婺准噙䔇唚崓崔昄鄘婉京庯䚺䩕唚闼幽橔喘時媹婔婻澇橬䚺䩕唚䔇庖枕䇽劯喉嘪䫘 UPDATE 敘桄昄扞橔劯嘪䫘婋麵䔇桹濘時媹䚺䩕唚㔗

5.5.2. 役鍴庖枕

襕役鍴婔婻庖枕嘪䫘婋麵認湙䔇变傴

ALTER TABLE products DROP COLUMN description;

婉䞇庖枕麯橬嘖昄扞鄘嚔潽崌启認婻庖枕䕩噿䔇亥溘幘嚔赆役鍴㔗婉誺套悩認婻庖枕赆埥婔婻臘䔇崡髞欔嚘䫘PostgreSQL 彍婉嚔锊劆婄役鍴臖亥溘㔗嘹埇傖锔誺嘪䫘 CASCADE 毺滯役鍴傂嘘冺蕡臖庖枕䔇婩薪

ALTER TABLE products DROP COLUMN description CASCADE;

埗黙誗5.11诙埡橬噿認底淉嘩脯劯䔇橺彽䔇媇敇㔗

5.5.3. 嵂媹亥溘

襕嵂媹婔婻亥溘媙釂嘪䫘臘亥溘臺濘㔗懫套

ALTER TABLE products ADD CHECK (name <> '');
ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no);
ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES product_groups;

襕嵂媹婔婻婉脘喍潊臘亥溘䔇麂䷺亥溘嘪䫘婋麵䔇臺濘

ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;

認婻亥溘儖䆋剿誕臯演昖欔傖臘婘時媹亥溘幋嬉媙釂严劽亥溘溇傽㔗

5.5.4. 役鍴亥溘

襕役鍴婔婻亥溘嘹驔襕䘖長垄䔇劉庖㔗套悩嘹敆䂟䂍庖垄埡庖劉庖闼幽庋愙儌冽䞔剘㔗劥彍嘹儌驔襕欆庺係䂘躻媘彖陉䔇劉庖㔗psql 䔇变傴 \d tablename 埇傖認婻婞媍噽垄毖埼埇脘幘柊冕庖演昖臘䔇䂖誗䔇桹濘㔗䇽劯儌滇認溇变傴

ALTER TABLE products DROP CONSTRAINT some_name;

套悩嘹婘崇䊖婔婻䫘潊䔇亥溘劉懫套 $2 彆媻庖嘹驔襕䂍垄時媹埯嚘埙螷垄潊婺婔婻橬昽䔇湺臖严㔗

启役鍴庖枕婔湙套悩嘹愿役鍴赆冺蕡䔇亥溘嘹驔襕䫘 CASCADE 㔗婔婻冋床滇昊婻崡髞亥溘冺蕡赆嚘䫘庖枕婪䔇嫇婔亥溘潡蔙婂髞亥溘㔗

鍴庖麂䷺亥溘崡欔橬亥溘䌂傋鄘認幽䫘㔗襕役鍴麂䷺亥溘埇傖認湙

ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;

襕螄冖麂䷺亥溘澇橬劉庖㔗

5.5.5. 櫹埻庖枕䔇䚺䩕唚

襕䂍婔婻庖枕螆䘞䚺䩕唚埇傖嘪䫘婔婻償婋麵認湙䔇变傴

ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77;

臙濘懟認幽啔婉嚔嘌巉傂嘘臘婺䯄橬䔇昄扞臯垄埻滇婺儖準䔇 INSERT 变傴櫹埻䚺䩕唚㔗

襕役鍴䚺䩕唚埇傖䫘

ALTER TABLE products ALTER COLUMN price DROP DEFAULT;

認湙垂鍙婪䕩嘷庯檪䚺䩕螆䘞婺䷺㔗䂷悩滇套悩潏傸役鍴婔婻誻澇橬垔幬䔇䚺䩕唚婉䞖髍臇啹婺䚺䩕锊劆儌滇 NULL 㔗

5.5.6. 媞櫹庖枕䔇昄扞䌂傋

檪婔婻庖枕蘸扵潊埥崡婔䓉昄扞䌂傋嘪䫘婋麵䔇变傴

ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);

埻橬婘庖枕麯䯄橬䔇懟婻釹鄘埇傖锊劆䔇蘸扵嘯桄䌂傋施欉埇脘潊媘㔗套悩驔襕敘崉溗䔇蘸扵嘹埇傖嵂媹婔婻 USING 床埖垄弄滯套嘘傯斓唚麯螇䞖桄唚㔗

PostgreSQL 儖臘商檪庖枕䔇䚺䩕唚(套悩庻婘)蘸扵潊桄䔇䌂傋誻橬潬埪臖庖枕䔇傂嘘亥溘㔗嘖滇認底蘸扵埇脘崌蘖潡蔙埇脘䫘潊喺攻䔇䂷悩㔗婘媞櫹昊庖枕䌂傋幋嬉嘹橔喘役鍴闼底亥溘䇽劯喉檪劽锗䔇亥溘時媹婪寂㔗

5.5.7. 麉变劉庖枕

麉变劉婔婻庖枕

ALTER TABLE products RENAME COLUMN product_no TO product_number;

5.5.8. 麉变劉臘

麉变劉婔婻臘

ALTER TABLE products RENAME TO items;

劯锔饡釕嬉誕
係䂘庖枕婪婔亓溄鍊