Oracle PLSQL Program Manual (SQL Daquan) (transfer)

xiaoxiao2021-03-06  100

Oracle PL / SQL Program Manual (SQL Daquan) (transfer)

A, SQLPLUS 1 Introduction   SQL command as the beginning of the following 17 statements keywords:  alterdroprevoke auditgrantrollback *  commit * insertselect commentlockupdate   create                                                                                                                   

 SQL not in SQL * PLUS command  These commands are not stored in the SQL buffer  @ definepause # delquit $ describeremark / disconnectrun acceptdocumentsave append editset breakexitshow btitlegetspool changehelpsqlplus clearhoststart columninputtiming computelistttitle connectnewpageundefine copy - --------  2                                          all columns in the base table created by users CATALOG                                                       SELECT     select  SELECT empno, ename, job fromemp;  select * fromdept orderbydeptnodesc;  logical operator  =  = or <> > > =  < <= ! et                                                                                                         slex job fromemp wherejobin ( 'clerk', 'analyst');  selectename, job fromemp wherejobnotin ( 'clerk', 'analyst')                                                                                             , salfromemp wheresalnotbetween2000and3000;  predicate like, not like selectename, deptnofromemp whereenamelike'S% ';  (beginning with a letter S)  selectename, deptnofromemp whereenamelike'% K ';  (ending K)  selectename, deptnofromemp whereenamelike'W ___';  (beginning with W, only three letter later)  selectename, jobfrom EMP  aales% '; (which employee's work name is not starting with Sales)         nullnull, ISNOT [NULL) No bonus (NULL) selectename, jobfromemp wherecommisnull;  selectename, jobfromemp wherecommisnotnull;  multi-criteria query  selectename, job From                               Select 5% of the bonus than its salary? Select    SELECT [ , Sal, Comm, Comm / Sal  From Offem  WHERENCOMM>

.05 * SAL                                                                                           Mar-87 Add                                                                                                                                             ? 6-Mar-87 6-Mar-87 15 / (24 * 60 * 60)  = alias  6-Mar 87and15secs-column names selectenameemployeefrom emp wheredeptno = 10;  (alias: employee)  selectename, sal, comm, comm / sal "C / SRATIO" fromemp wherecomm> .05 * sal order                               display the current SQL command, and put the fourth line as the current line, There is a * behind this line number.  changeorc original first time with the new content occurs in a row replacement content  SQL> c / (...) / ( 'analyst') /  inputori increase in one or more rows           Del   Del  Delete the current line in the SQL buffer             running the SQL buffer in the SQL buffer Edit writes commands in the SQL buffer to text files under the operating system, and call the editor provided by the operating system to perform modifications.

  -------------  3        @sert                                                                               dept (dname, deptno)  values ( 'accounting', 10);  selected insert data from other tables  insertintoemp (empno, ename, deptno)  selectid, name, department FromOld_emp                                       SQL / PLUS will be for each parameter s when the user is prompted parameters or character data corresponding to the date, the parameter may be added to the quote, without quotation marks  insertintodept values ​​can be input (& deptno, '& dname', '& loc');  inserted Null (NULL)                       Download Data Default Format: DD-MON-YY INSERT EMP (Empno , ename, hiredate)  values ​​(7963, 'stone', '07-APR-87');  system time: SYSDATE insertintoemp (empno, ename, hiredate)  values ​​(7600, 'kohn' , SYSDATE);  data update  updateemp setjob = 'manager' whereename =' martin ';  updateemp setjob =' marketrep' whereename = 'salesman' ; Update EMP = 40, Job = 'market  r  j =' salesman '; Data Deletion  DELETE                           Update submission  Submit Method             @ inesRT, Update, Delete will be submitted immediately.  Update cancellation                                      creating a base table DEPTNONUMBER (2),   DName JaChar (14),   LOCTCHAR (13));   Data Dictionary automatically update. A base table is up to 254 columns.  Name name name naming rules:   The first character must be a letter, which can be arbitrarily (including         ".  Name must not exceed 30 characters.  The only user's base table name must be unique, can't be the reserved word of Oracle, the column names of the same base table are different.  Use Double Quotes  If the table name is enclosed in double quotes, the above rules can be not met;  Only the use of double quotes can distinguish large, lower-write;

  data type: CHAR (N)     Number (N, D)                                              null value processing  Sometimes the value of the value Cannot be empty Create_Number (2)                                     Add a list in the base Table   ALTERTABLE dept add (headcntnumber (3));  modify an existing column attributes  altertabledept modifydnamechar (20);  Note: only when all the values ​​in a column is empty, Can reduce its column value width.  Only the type of column value can be changed when all values ​​are empty.  Only the list as NOT-NULL can only be defined when all values ​​are not spaced. Example s:  altertabledeptmodify (locchar (12));  altertabledeptmodifylocchar (12);  altertabledeptmodify (dnamechar (13), locchar (12));  create a view  createviewmanagersas selectename, job, sal fromemp wherejob = 'manager';  alias names for the view columns  createviewmydept (person, title, salary)  asselectename, job, sal fromemp wheredeptno = 10;  withcheckoption s options use withcheckoption, To ensure that the view is inserted or updated, the data must meet the conditions specified in the select command in the view definition.                                                    Update DEPT20 occurs when doing the following  setdeptno = 30 whereename = 'ward'; s copy s base table, view createtableemp2 asselect * fromemp;  base table, delete the view  droptable   DROPVIEW    ------------   SQL * Plus report function  SQL * PLUS Some basic format command   DEPTNO     DEPTNO enameheadingname columnsalheadingsalary columnsalformat $ 99,999.00 ttitlesamplereportfor | hitechcorp btitlestrictlyconfidential breakondeptno computesum ofsalondeptno run headers and footers  ttitlesamplereportfor | hitechcorp btitlerightstrictlyconfidential "|" represents a new line, the end does not have to add a semicolon  options There are three types: left center  using TTITLE, the system will automatically display the date and page number at the top of each page.   TTITLET and BTITLE commands are valid until the header or tail is reset, or exit SQL * Plus.

 title the following command to make the statement invalid  TTITLEOFF BTITLEOFF column name  column defined command is used to display the column names  if the name is a word, do not add quotation marks  columnenameheadingemployee columnename heading'employee | name' (| linefeed)   columnenameformatA15 columnsalformat cancel column format defined  columnenameclear column $ 9,999.99 columncommlike SAL \ Like clause makes a column format refers to another column format, it copies the column name and its format                    selex  DEPTNO, ENAME    SELECT DEPTNO, ENAME  emp orderbydeptno;  (ORDERBY clause for controlling BREAK) s shown as  10clark niller 20smith scott 30allen blake only one command from BREAK Role, but once can be used on multiple columns                 deptno      deptno   SELECT DEPTNO, ENAME    orderbydeptno; two blank spaces  clearbreak (canceled BREAK command) between  each deptno  breakonpage (each time starting a new page)  breakonreport (each from a new report start)  breakonpageonreport (joint use)   breakondeptnoskip2 computesumofsalondeptno grouping calculate calculate each department The sum of salary is separated by the information between the SKIP clause to separate the information between the department                                 MAX  MINM MIN   STD                         Once a compute is defined, it has been valid until it shuts down Compute (Clear )  SQL / PLUS environment command   show option s (display current parameter settings case)  showall (All values ​​are displayed) s s setting parameter values ​​or options  set  setautocommiton SET switch command comprises  setautocommit {off | on | immediate}  (automatic submission, OFF default)  setecho {off | on}  (command file execution, whether the command itself, OFF default in the terminal)  setfeedback {off | on}  (ON: the end of the query, the results are given, the number of information recording, by default;  OFF: no query result, the number of information recording)  setheading {off | on}  (ON: column header Displayed on the report, default; OFF: Not displayed on the report)        The maximum number of characters displayed in a row,

The default is 80.PageSize {n} The number of rows per page, the default is 14 {OFF | ON | text} (ON: When the report exceeds one page, each display screen Suspend the display, wait for the user to return the vehicle button, then display;                                                                                                                                        ? Command buffer, usually, the SQL command buffer has been the current buffer.  Since the SQL command buffer can only store a SQL command, it is possible to store SQL commands and SQL * PLUS commands with other buffers.  Regularly used settings can be placed in the Login.sql file.                                            The commission of no commissions in department 30 is "NO DATA".   set Null is the SQL * Plus command, with it to identify null values ​​(NULL), which can be set to any string.  Save command SAVE save file name  input 1selectempno, ename, job 2fromemp 3wherejob = 'analyst' saveresearch directory will add a research.sql file.  Edit Command EDIT  EDIT  Edit the content in the current buffer.  Edit a file              get GET  ASEARCH to transfer the file content on the disk into the buffer, and display it on the screen, the file name does not have to add .sql.   START command  Run the specified file  START                   not only display the query results, but also save the result to file   SPOOLFF  The result is output on the printer, first deposit them in a file, then do not have to use spool FF, and use: spoolout spoolOut Close this file and outputs the production report on the system default printer                                                                                                      \ intoemp (empno, ename, deptno)  values ​​(3333, 'samson', 20);  spoolnew_emp select * fromemp wheredeptno = 20 ordeptnoisnull     spool            ------  6                                                                                                     One letter is changed to uppercase.   Jack  Smith - jack                                                    

 substr (job, 1,4);   lower upper least other strings taken alphabetical list at the top of a string  greatest removed alphabetical list of strings in the last row of a Skewers Date Function  Add_MONTH (HIREDATE, 5)   Month_between (Sysdate, HiRedate)   Calculate the number of months between employment time and system time                          NEXT_DAY (HIREDATE, 'Friday')             NEXT_DAY (HIREDATE, 'FRIDAY')  Date of the first Friday after calculating the date of employment   SELECT [SESDATE, 'Friday')                                                                                                                               to_char not function, default date format in ORACLE is' DD_MON_YY' to_char (date, datepicture)  selectename, to_char (hiredate, 'DyMondd, yyyy') hired fromemp                                                                                                                         Date data format  DD   dy  DY  DDSPTHTWELFTH MM03 MON  MONTHMARCH YY                                                                'Mondd, yyyy' MAR12,1987'MONdd, yyyy' ThursdayMARCH12'DayMONTHdd' Mar1211: 00 am'Monddhh : miam' Thu, thetwelfth'Dy, "the" ddspth' arithmetic function  least (v1, v2)  selectename, empno, mgr, least (empno, mgr) lownum fromemp WHERE-     NG value function   NVL (V1, V2)   NVL (V1, V2) V1 is column name, if V1 is not a null value, NVL returns its column value.   V1 is null, return to V2 value.

                                                       Poly group functions  minmaxcount be used for any type of data  selectmin (ename)  fromemp;  selectmin (hiredate)  fromemp;  selectmin (sal)  fromemp;  number Is there a job? SELECT (JOB)      How many different types of work? Select                               other agglomerations (Digital Data)   Calculate average wage SELECT_EMP; STDDEV  calculation of the average difference of salary                                                                             Group                  Employee of each department  SELECT DEPTNO, Count (COUNT) SELECT DEPTNO, COUNT (SAL) *           Employees of each department of each department Select  DEPTNO, Job, count (*)                                        Conditional group  (where is for SELECT, Having is a for groupby)   Which departments have more salary and more than 9000 select  deptno, sum (sal) Sum (SAL)> 9000; SELECT small junction  Remove staff, which department's total salary is more than 8000 SELECT DEPTNO, SUM (SAL)                              group = 'clerk'  groupby       havingsum (sal)> 8000 orderbysum (sal);  ---------  7 advanced query  equivalent join  selectempno, ename, job, emp.deptno , dname fromemp, dept whereemp.deptno = dept.deptno; s outer coupling  selectename, dept.deptno, loc fromemp, dept whereemp.deptno ( ) = dept. DEPTNO;  If there is a value in dept.deptno, there is no in Emp.Deptno (such as deptno = 40), and the result will generate an null value in the result of the results: the same base table Have to do it Connect, you can use the self-join            manger.ename, manager.ename = manager.empno;         manger       s value which is coupled wages of employees belonging to the third level  selectename, sal fromemp, salgrade wheregrade = 3 andsalbetweenlosalandhisal;  (base table salgrade: grade Losal  

Connection set operation s s s set operation line to two or more query results into one  union-setunion Rowsoffirstqueryplusofsecondquery, lessduplicaterows  intersect-setintersection Rowsbothquerieshaveincommon minus-setdifference rowsuniquetothefirstquery ​​describes several views  accountview enamesal Job                 returned to a query result, combined with records in the base table or view  all sectors in which employees earn more than 2000 corresponding column data types must be the same  selectename, sal fromaccount wheresal> 2000 union selectename, sal fromresearch wheresal > 2000 union                                                                                INTERSECTOTOMIBOUNSETOUSETOUSETOUSETOUSETOUNSET                        The partial record of the second query result is different in the first query results.

 What kind of work is in the Terrorist, but not in the sales department?  selectjobfromaccount minus selectjobfromsales;  subquery  slectename, deptno fromemp wheredeptno =  (selectdeptno fromemp whereename = 'smith'); multi-level query  select   select                                                                                                                                      ? >  (selectsal fromemp whereename = 'clark');  plurality of base tables and subqueries  selectename, job, sal fromemp, dept whereloc = 'new york' andemp.deptno = dept.deptno andsal>  (selectsal fromemp whereename = 'scott');  subquery using poly-function  selectename, hiredate   eMP                                                                       Register, create a new foundation Table  CONNECT, registration, and inquiry  Only DBA has the right to create new users                  dba or user can change the user password? Grant connecttoscott identifiedbyleopard;  base table permissions 1 there are two ways to obtain permission for the operation of the base table to create your own base table    obtain permission to create user base table of grantselect, insert        These privileges   select                  selex      SELECT *         Creating synonyms   Create a synonym EMPLOYEEEE  CRE for users Allen Ate_Synym EMPLOYEE  alLlen.emp  You can make other users have such power, that is, other users can grant your base table authority to others                                         grand   scott withgrantoption;   recover permissions system permissions   recover only the DBA privilege  base table can always withdraw  revokeinsert onemp fromscott;  -------- -9 9   Create                                   About indexes (at least 50 records To establish an index, insert data   Establish any number of indexes for a base table  Generally, the index is established as the primary key  Establish an index, it does not affect the execution of the SQL command. After the index is established, Oracle is automatically maintained and used. Index  Ensure that the data uniqueness increases the execution speed, the index can also ensure that each column value in each record is not repetitive.                                                                                   ? If there is, arrange it according to the descending order of salary.

 If there are more than two employees pay the same, they are sorted by their name. Select                                             List the percentage of employee names and bonuses accounted for a percentage.   Require display time columnnamism clearly, sorted by employee name, excluding an unknown employee. Select                           Work in Chicago (Department 30) in Chicago (Department 30) All employees' salary rose 10%.  updateemp setsal = 1.1 * sal wheredeptno = 30;  updateemp setsal = 1.1 * sal wheredeptno = (selectdeptno fromdept whereloc = ' Chicago '); To Hitech newly built a department, numbered 50, and other information are not known.  insertintodept (dname, deptno)  values ​​( 'faclities', 50);  create a view, three column name, which does not include the employee information  createviewemployee ( "employeename",  " Employee   "" Employee Job ")                            Make a wage report, including employee name, employment time (press Week calculation), wage and department number, one page shows the information of a department, the end of each page, the sum of the wages of the page, and the sum of the employment time,                                                        Time summary,   wage calculate according to US dollars, employment time is calculated according to week, and there should be titles per page.  ttitle'service' breakondeptnoonpageonreport computesumofsalondeptno computesumofsalonreport computesumof service_lengthondeptno computesumofservice_lengthonreport columnsalformat $ 99,999.00 columnservice_lengthformat9999 selectdeptno, enameemployee, (sysdate-hiredate) / 7                                                                                                                                                   YYYY, the total income includes the total income of employees without bonuses, named alphabetical order.

"Hirepha -date" format                                      "EMPLOYEE",   "EMPLOYEE",   (SAL NVL (COMM)   "EMPLOYEE" , 0) "Compensation",    "hiredate"  "hirephar Date"                  Lists more than 7 surrounding countries Name and area.  selectnation, area fromnation wherecodein (selectnation_code fromborder groupbynation_code havingcount (*)> 7);  lists all equal area larger than Japan The national name and population of the island country.  selectnation, population fromnation, border wherecode = nation_code ( )  andnation_codeisnull andarea> =  (selectarea fromnation whereupper (nation ) = 'Japan');  List all the borders in other countries, and show their border countries.

 breakonnation selectnation1.nation,  nation2.nationborderin_country fromnationnation1, border, nationnation2 wherenation1.code = border.nation_code andborder.border_code = nation2. Code      -----------  -----------  PL / SQL 2PL / SQL block structure and data type The characteristics of block structure  Nested                        end;        No more than 30 characters  The first character must be letters                                                          Can be arranged, and unparalleled in the case. No SQL reservation word                                      single quote s zero-length string (no characters between the two single quotes), said NULL character:   1 length string of data definition syntax s s identifier [constant>  data type [NOT NULL> [: = PL / SQL expressions>;  ': =' s represent variables are assigned numeric data types include s number (7,2)  character char (120)  date type Boolean date Boolean (value True, False or NULL, not stored in the database) notnull: = false;  availableboolean;  (initial value NULL) % type matching the type  books_printednumber (6);  books_soldbook_printed% type;  manager_nameemp.ename% type;  variable Assignment Variable Name: = PL / SQL Expression  Numvar: = 5; BOOLV Ar: = true; Datevar: = '11-jun-87';   Null value in digital expression  null = NULL (null value plus number is still empty)   null> < Number> = null (null value is compared, the result is still null)   NULL || 'string' = 'string' (NULL '')     (null value is connected to the string, the result is Original string)   Variable scope   The identifier is valid in the declaration. If the identifier is not redefined in the sub-block, it is also effective in all sub-blocks of the PL / SQL block. The logo after redefining the identifier. The scope of action is only effective in this sub-block.                                ? '

President '; eXception                                                                                                                                                );  begin selectempnointov1fromemp wherejob = 'manager';  exception whentoo_many_rowsthen insertintojob_errors values ​​( 'morethanonemanager '); End; Exception                                                            ----  3SQL and PL / SQL inserted  declare my_salnumber (7,2): = 3040.55;  my_enamechar (25): = 'wanda';  my_hiredatedate: = '08 -SEP-88 '; begin INSERT in in (Empno, Enmae, Job, HiRedate, Sal, Deptno)   VALUES (2741, My_ENAME,' CABDRIVER ', MY_HIREDATE, MY_SAL, 20);   End ; s delete  declare bad_child_typechar (20): = 'naughty';  begin deletefromsantas_gift_listwhere kid_rating = bad_child_type;  end;  transaction  commit [WORK>;  rollback [WORK> ;  (optional WORK keyword, but has no effect on command execution)  savepoint tag name; (save the current point)  marks the current point in the transaction  rollback [WORK> to [SAVEPOINT>  tag name (Return to the current save point)  All the modifications of the database after the savePoint command  Keyword Work and SavePoint are optional, execute the command S function has no effect  PL / SQL block SQL commands can be used for all functions  insertintophonebook (lastname) value (upper (my_lastname));  selectavg (sal) intoavg_salfrom EMP;  For non-SQL commands, most individual functions can be used            x: = SQRT (Y); LastName: = Upper (lastname); age_diff: = months_between (birthday1, birthday2) / 12; s assignment of data type conversion  4 Species assignment form: s variable name: = expression  insertinto yl table values ​​(expression 1, expression 2 ,. ..); UPDATE                                                                Number  Number Transfer into Char  CHAR MTE to CHAR_VAR: = NM_VAR; Digital Conversion Brand Type Date_Var: = '25-DEC-88';

  Character conversion into date type                                                                                                       Example  declare num_jobsnumber (4);  begin selectcount (*) intonum_jobsfromauditions whereactorid = && actor_idandcalled_back = 'yes';  ifnum_jobs> 100 then updateactorsetactor_rating = 'wordclass' whereactorid = && actor_id;  elsifnum_job = 75then updateactorsetactor_rating =' daytimesoaps' whereactorid = && actor_id ;  else updateactorsetactor_rating = 'waiter' whereactorid = && actor_id;  endif;  endif;  commit;  end;  --------  5 Circulation      End                                                                                                                                              3): = 0; begin @Sert  inToTable1Values ​​('TastesGreat'); INSERT             filling '); CTR: = CTR 1;     End                                                                                                                             ...  endloop;  declare my_indexchar (20): = 'fettucinialfredo';  bowlchar (20);  begin formy_indexinreverse21..30loop INSERT  INTOTOTEMP (COLL ) values ​​(my_index);  / * cycles from 30 to 21 * /  endloop;  bowl: = my_index;  end;  with digits after inreverse must be ascending order, must be Is integer, can not be variables or expressions ----------                                                                                                                                   notfound% found% rowcount% isopen embodiment  fetchmy_curintomy_var;  whilemy_cur% foundloop (data processing)  fetchmy_curintomy_var;  exitwhenmy_cur % rowcount = 10;  endloop; % notfound s attribute values ​​as follows:  fetch operation returns no record, a record of the value returned true fetch operation, then the value is not on the cursor fetch false Take the value of NULL

                             Note: If there is no Fetch action, % notfound will result in an error,   Because% NOTFOUND is NULL. Close the cursor                                                                                                           a set of commands>   Where:   index is built on the value above each record, the record name does not have to declare the record name, the column name, initialization tour finger open the cursor                                                                                          SG Store information about the latest SQL command          sql% notfound  SQL% NOTFOUND   SQL% NOTFOUND                                                                                                 sql% isopen:        sql% isopen: Taken The value is always false. The SQL command is executed, and the PL / SQL immediately turns off the implicit cursor.  ---------  7                      Where you_are_here is to jump, the label must be in the same set of commands, or in the same block. correct use  <> (reference)  x: = x 1 ifa> bthen b: = b c;  gotodinner;  endif;   gotojail error using ;  ifa> bthen b: = b c;  <> (reference)  x: = x 1;  endif;  numeral: the significance Fuzzy s numeral values ​​may be used to define the column variable  <>  declare deptnonumber: = 20;  begin updateempsetsal = sal * 1.1 wheredeptno = sample.deptno;  commit;  endsample;  numerals and if not Number Limit, this command will modify each record.

  ----------  8. Pre-defined abnormal situation  No Oracle error will automatically generate an exception information  some abnormal conditions have been named, such as:   no_data_found  When SELECT statement is not returned When you record it, it is generated to define a cursor, while the SELECT statement returns a plurality of records. WHENEVER         User-defined anomalies   By the user's own partial definition:   declare   declare   declare    declare  x Number;            User-defined anomalous case Follow the general scope rule  Obtain an exception: Raise_Something_ISNT_Right  Note: You can also get predefined exceptions   EXCEPTION_INIT statement  Allow Oracle errors s call naming format:  pragmaexception_init (,);  Example  declare deadlock_detectedexception;  pragmaexception_init (deadlock_detected, -60);  raise the RAISE command statement s alone, can be acquired again Current abnormal conditions (like an abnormal situation are repeated).  This statement can only be used separately in an exception handling.  Other Processing Identifier  A set of statements for processing exceptions:                                                                 Othersphade - Last Processing   "Group of Statements> End; End the PL / SQL block part, but also end the abnormal processing part --------          Receive Contract_no and item_no value, look in the inventory table, if the product:  has shipped,  assigned to seven days after ordering today in arrival_date, the assignment today after a month  in arrival_date in neither order nor delivery, Then assign a value in arrival_date to two months later,   increasing a new order record in the ORDER table.

 product_status column values ​​of 'shipped' and 'ordered' inventory:  product_idnumber (6)  product_descriptionchar (30)  product_statuschar (20)  std_shipping_qtynumber (3)  contract_item:  contract_no number (12)  item_nonumber (6)  arrival_datedate order:  order_idnumber (6)  product_idnumber (6)  qtynumber (3)  answer:  declare i_product_idinventory.product_id % type;  i_product_descriptioninventory.product_description% type;  i_product_statusinventory.product_status% type;  i_std_shipping_qtyinventory.std_shipping_qty% type;  begin selectproduct_id, product_description, product_status, std_shipping_qty intoi_product_id, i_product_description,  i_product_status, i_std_shipping_qty frominventory whereproduct_id = ( selectproduct_id fromcontract_item wherecontract_no = && contractnoanditem_no = && itemno);  ifi_product_status = 'shipped'then updatecontract_item SET-ar ar = itex;                                                                          c      tem setarrival_date = add_months (sysdate, 1)  whereitem_no = && itemnoandcontract_no = && contractno;  else updatecontract_item setarrival_date = add_months (sysdate, 2)  whereitem_no = && itemnoand contract_no = && contractno;  insertintoorders values ​​(100, i_product_id, i_std_shipping_qty);  endif;  endif;  commit;  end;  2:  1. identify all the specified sectors Employee  2. Use the variable with '&' to prompt the user input department number  3. Switch the employee name and wage into the PRNTTable table, the base structure is: Create_TablePlePle (7), LINE       4. Experient situation, the employee information of the bonus is not null value can be deposited in the PRNTTABLE table.

 answer:  declare cursoremp_curis selectename, sal, comm fromempwheredeptno = & dno;  emp_recemp_cur% rowtype;  null_commissionexception;  begin openemp_cur;  FetchEmp_Cur                                  fetchemp_curintoemp_rec;  endloop;  closeemp_sur;  exception whennull_commissionthen openemp_cur;  fetchemp_curintoemp_rec;  while (emp_cur% found)  loop ifemp_rec.commisnotnullthen insertintotempvalues ​​(emp_rec.sal, emp_rec.ename);  endif;  fetchemp_curintoemp_rec;  end loop;  closeemp_cur;  commit;  end;    Java Research organization - Copyright 2002-2002RE: ORACLE database objects and user management (rpm)

Author: UB Time: 2003-08-14 21:06:59 [modify] [Reply] [Delete] ORACLE database objects and a user management, content management and major ORACLE database schema objects of the maintenance of this section is on ORACLE database The mode object management and maintenance, including: tablespace, table, view, index, sequence, synonym, aggregation, and integrity constraints. For each mode object, the definition is described, which describes its function, and finally how to manage them in the SQL language-based instance. 1.1 The tablespace is necessary to maintain it first because the table space is a logical space containing these mode objects. Create a table space   sql> createphablespace   @ '/ usr / usr / oracle / dbs / jxzy.dbf'> online; modified table space  sql> altertablespace jxzy @tablesNormal; SQL> AltertableSpace                 / usr / oracle / dbs / jxzy.dbf '> to' / usr / oracle / dbs / jxzynew.dbf '> Online SQL> CREATETABLESPACE                             > DROPTABLESPACE JXZY> INCLUDINGTENTENTS 1. 图片 2 The table maintenance table is the basic unit of data storage in the database, and a table contains several columns, each column name, type, length, etc. The establishment of the table  sql> createphable (> office_num                                   NOT / NULL); SQL> Altertable    SQL> Alter_Table                                            cascade constraints // Delete The integrity constraints of other tables of the table are referenced 1.  3 The view maintenance view is a collection of data generated by one or several base meters, but the view does not account for storage. Create a view to protect data security (only some of the ranks that you can see), simplify the independence of the query operation and protect the data. View of the view   sql> create    (selectpole_path_num 安                                                                                                                                              ASPATH, WELL asSupport_Device asFrom:       SQL> DROPVIEW; 1.4 sequence maintenance sequence is the unique integer generated by the sequence generator.

Establishing  sequence SQL> CREATESEQUENCEjxzy.sequence_cable> STARTWITH1> INCREMENTBY1> NO_MAXVALUE; established sequence, jxzy.sequence_cable.currval returns the current value, jxzy.sequence_cable.nextval return current The new value of the value after 1 is added. SQL> alter_cable> Start_1 // The starting point cannot be modified, if you modify, you should delete, then redefine> IncTement 2> MaxValue_1000; Deletion of the Sequence  SQL> DROPSQUENCE     sSEquence_cable 1. 5 5  The index maintenance index is a structure associated with the table, which is established to improve the speed of the data. Therefore, in order to increase the index speed on the table, one or more indexes can be created on the table, and an index can be built on one or more columns. For the query type, establish multiple indexes, greatly improve the query speed, the updated table, if the index is too large, will increase the overhead. Index unique index and unique index index creation  SQL> Create     ipspace (switch_name)> TableSpace                                                                                                 \ (office_num, switch_name> TABLESPACE jxzy; Index Delete  SQL> DROPINDEX jxzy.idx_switch; 1. 6 完 完 约 约 约 管理 管理 管理 正 正 正 正 正 性 性 性 性 性 性 性 性; Data Type Check Prevents data in the database from doing semantics. Integrity constraints are defined a set of rules description methods for columns.

ORACLE provides the following integrity constraint. A.NOTNULL b.UNIQUE non-null primary key unique key c.PRIMATYKEY a table can have a non-empty outer d.FOREIGAKEY The key E.CHECK                                                                                                                                               NN_DESC  not  NN_DESC  not  NN_DESC   SQL> altertable    SQL> altertable /                                                                                                                          witch (switch_code   u ((8)> constraint                                                                                                                                          NUMBER (8),> office_numnumber (3)> CONSTRAINTfk_officenum> REFERENCESoffice_organization (office_num)> ONDELETECASCADE); define inspection  SQL> CREATETABLEoffice_organization (> office_numNUMBER (3) ,> CHECK                                二 二 9 数据 数据 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户 用户management system is configured with a good security mechanism 2.1ORACLE database security policy to establish system-level security guarantees  system-level privileges is achieved by granting user rights system-level, system-level rights (the system privileges) includes: establishing Table space, build users, modify users' rights, delete users, etc. System privileges can be granted to users, or they can be recycled at any time. Oracle system privileges 8 More than 0. Establishing an object-level security guarantee  Object-level privilege is achieved by granting the user's right to operate (query, increasing, deleting), etc. in the database. Establish user-level security guarantee  User-level security guarantee through user passwords and role mechanisms (a set of rights). The purpose of introducing role mechanism is to simplify authorization and management of users. The practice is to packet the user according to its function, establish a role for each user, and assign the role to the user, and the same role has the same privilege. Content 2.2 User Management ORACLE user management including user creation, modification and deletion of users to establish  SQL> CREATEUSERjxzy> IDENTIFIEDBYjxzy_password> DEFAULTTABLESPACEsystem> QUATA5MONsystem;          sql> create                                        sql> DROPUSER  JXZYCASCADE;         simultaneously delete its established entity 2.3 System privilege management and control Oracle offer more than 80 system privileges, each of which allows users to perform one or a type of database operation.

转载请注明原文地址:https://www.9cbs.com/read-126331.html

New Post(0)