• Tidak ada hasil yang ditemukan

Modifying DB2 data

Dalam dokumen Application Programming and SQL Guide (Halaman 77-80)

Thesetopicsdiscuss howtoinsert,update,and deletedatainanexistingtableby usingSQLstatements:

v “Insertingrows:INSERT”

v

“Updatingcurrentvalues:UPDATE”onpage44 v

“Updatingexistingdataand insertingnewdata:MERGE”onpage45 v

“Deletingrows:DELETEand TRUNCATE”onpage46

Inserting rows: INSERT

Use anINSERTstatementtoaddnew rowstoa tableorview.UsinganINSERT statement, youcando thefollowingactions:

v Specifythecolumnvaluestoinsertasingle row.Youcanspecifyconstants,host variables,expressions,DEFAULT,orNULLbyusingtheVALUESclause.

“Insertingasinglerow”onpage40explainshowtousetheVALUESclauseof theINSERTstatementtoaddasingle rowofcolumnvaluestoa table.

|

|

v Inan applicationprogram,specifyarrays ofcolumnvaluestoinsertmultiple rowsintoa table.“Insertingmultiplerowsofdatafromhostvariablearrays”on page109explainshow tousehostvariable arraysintheVALUESclauseof the INSERTFORnROWSstatementtoaddmultiple rowsofcolumnvaluestoa table.

v IncludeaSELECTstatementintheINSERTstatementtotellDB2 thatanother tableorviewcontains thedataforthenewrow orrows.“Insertingrowsintoa tablefromanothertable”onpage41explainshow tousetheSELECTstatement withinanINSERTstatementtoaddmultiplerowstoatable.

Ineachcase, foreveryrowthatyouinsert,youmustprovidea valueforany column thatdoesnothaveadefaultvalue. Foracolumn thatmeetsoneofthe followingconditions, specifyDEFAULT totellDB2toinsertthedefaultvaluefor thatcolumn:

v Thecolumnisnullable.

v Thecolumnisdefinedwith adefaultvalue.

v Thecolumnhasdatatype ROWID.ROWIDcolumns alwayshavedefault values.

v Thecolumnisan identitycolumn.Identitycolumnsalways havedefaultvalues.

v

Thecolumnisa rowchangetimestampcolumn.

The valuesthatyoucaninsertintoa ROWIDcolumn,anidentitycolumn,orarow changetimestampcolumndependonwhetherthecolumnisdefinedwith

GENERATEDALWAYS orGENERATEDBYDEFAULT.

For moreinformationaboutinsertingdataintoROWIDcolumns,see“Inserting datainto aROWIDcolumn”onpage42.

For moreinformationaboutinsertingdataintoidentitycolumns, see“Inserting datainto anidentitycolumn”onpage43.

Fore moreinformationaboutrowchangetimestampcolumns,seethetopic

“CREATE TABLE”inDB2SQLReference.

Inserting a single row

YoucanusetheVALUESclauseoftheINSERTstatementtoinsertasingle rowof column valuesintoa table.Youcaneithernameallofthecolumnsfor whichyou are providingvalues,or youcanomitthelistofcolumnnames.Ifyouomitthe column namelist,youmust specifyvaluesforall ofthecolumns.

Recommendation: ForstaticINSERTstatements,nameallofthecolumns for whichyouareprovidingvaluesforthefollowingreasons:

v YourINSERTstatementisindependentofthetableformat.(For example,youdo notneed tochangethestatementwhena columnisaddedto thetable.)

v Youcanverifythatyouarespecifyingthevaluesinorder.

v

Yoursourcestatementsare moreself-descriptive.

Ifyoudonotnamethecolumns inastaticINSERTstatement,and acolumnis added tothetable,anerrorcanoccurif theINSERT statementisrebound.An errorwilloccurafter anyrebindof theINSERTstatementunlessyouchangethe INSERT statementtoinclude avalue forthenew column.Thisistrueevenif the new columnhasa defaultvalue.

Whenyoulistthecolumnnames,youmust specifytheircorrespondingvaluesin thesameorderasinthelistofcolumnnames.

|

|

|

|

|

Example:Thefollowingstatementinsertsinformationabouta newdepartment into theYDEPTtable.

INSERT INTO YDEPT (DEPTNO, DEPTNAME, MGRNO, ADMRDEPT, LOCATION)

VALUES (’E31’, ’DOCUMENTATION’, ’000010’, ’E01’, ’ ’);

Afterinsertinganew departmentrowintoyour YDEPTtable,youcanusea SELECTstatementtoseewhatyouhaveloadedintothetable.ThefollowingSQL statementshowsyouallofthenewdepartmentrowsthatyouhaveinserted:

SELECT *

FROM YDEPT

WHERE DEPTNO LIKE ’E%’

ORDER BY DEPTNO;

Theresult tablelookssimilartothefollowingoutput:

DEPTNO DEPTNAME MGRNO ADMRDEPT LOCATION

====== ==================================== ====== ======== ===========

E01 SUPPORT SERVICES 000050 A00

---E11 OPERATIONS 000090 E01

---E21 SOFTWARE SUPPORT 000100 E01

---E31 DOCUMENTATION 000010 E01

---Example:Thefollowingstatementinsertsinformationabouta newemployeeinto theYEMPtable.BecausetheWORKDEPTcolumnisaforeign key,thevalue thatis insertedforthatcolumn(E31)must bea valueintheprimarykeycolumn,which isDEPTNOintheYDEPTtable.

INSERT INTO YEMP

VALUES (’000400’, ’RUTHERFORD’, ’B’, ’HAYES’, ’E31’, ’5678’, ’1998-01-01’,

’MANAGER’, 16, ’M’, ’1970-07-10’, 24000, 500, 1900);

Example:Thefollowingstatementalsoinsertsarow intotheYEMPtable.Because theunspecifiedcolumns allownull values,DB2 insertsnull valuesinto the columns thatyoudo notspecify.

INSERT INTO YEMP

(EMPNO, FIRSTNME, MIDINIT, LASTNAME, WORKDEPT, PHONENO, JOB)

VALUES (’000410’, ’MILLARD’, ’K’, ’FILLMORE’, ’D11’, ’4888’, ’MANAGER’);

Inserting rows into a table from another table

Youcancopydatafromonetableintoanothertable.Usea fullselectwithin an INSERT statementtoselectrowsfromonetable toinsertintoanothertable.

Example:ThefollowingSQLstatementcreatesa tablenamedTELE:

CREATE TABLE TELE

(NAME2 VARCHAR(15) NOT NULL,

NAME1 VARCHAR(12) NOT NULL,

PHONE CHAR(4));

ThefollowingstatementcopiesdatafromDSN8910.EMPintothenewlycreated table:

INSERT INTO TELE

SELECT LASTNAME, FIRSTNME, PHONENO

FROM DSN8910.EMP

WHERE WORKDEPT = ’D21’;

Thetwopreviousstatementscreateandfill atable,TELE,thatlooks similartothe followingtable:

NAME2 NAME1 PHONE

=============== ============ =====

PULASKI EVA 7831

JEFFERSON JAMES 2094 MARINO SALVATORE 3780 SMITH DANIEL 0961 JOHNSON SYBIL 8953 PEREZ MARIA 9001 MONTEVERDE ROBERT 3780

The CREATETABLEstatementexamplecreatesa tablewhich,atfirst,isempty.

The tablehascolumns forlastnames,first names,and phonenumbers,butdoes nothaveanyrows.

The INSERTstatementfills thenewlycreated tablewithdatathatisselectedfrom theDSN8910.EMPtable:thenamesand phonenumbersofemployeesin

departmentD21.

Example:ThefollowingCREATEstatementcreates atablethatcontains an

employee’s departmentnameandphonenumber.ThefullselectwithintheINSERT statementfills theDLISTtablewith datafromrowsthatareselectedfromtwo existingtables, DSN8910.DEPTandDSN8910.EMP.

CREATE TABLE DLIST

(DEPT CHAR(3) NOT NULL,

DNAME VARCHAR(36) ,

LNAME VARCHAR(15) NOT NULL,

FNAME VARCHAR(12) NOT NULL,

INIT CHAR ,

PHONE CHAR(4) );

INSERT INTO DLIST

SELECT DEPTNO, DEPTNAME, LASTNAME, FIRSTNME, MIDINIT, PHONENO

FROM DSN8910.DEPT, DSN8910.EMP

WHERE DEPTNO = WORKDEPT;

Dalam dokumen Application Programming and SQL Guide (Halaman 77-80)