Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Distributed Database Applications COSC 5050 Week Seven Outline Dynamic SQL and dynamic PL/SQL NDS statements EXCUTE IMMEDIATE OPEN FOR Oracle's object features Globalization and localization Webster University Distributed Database Applications Jiangping Wang Dynamic SQL and PL/SQL Constructed and executed at runtime Stored in character strings that are input to, or built by, the program at runtime Execute DDL statements Build back-ends applications DBMS_SQL package Native Dynamic SQL (NDS) Webster University Distributed Database Applications Jiangping Wang NDS Statement Native dynamic SQL Is an integral part of the PL/SQL language itself Significantly simpler to user and faster Non-query statements (DML and DDL) and PL/SQL blocks EXECUTE IMMEDIATE statement Execute a specified SQL statement immediately OPEN FOR statement Perform multiple-row dynamic queries Webster University Distributed Database Applications Jiangping Wang DDL, DML, Anonymous Blocks declare l_sqlstring varchar2(200); l_plsqlblock varchar2(200); begin execute immediate 'create table execute_table (col1 varchar(10))'; for l_counter in 1..10 loop l_sqlstring := 'insert into execute_table values (''row ' || l_counter || ''')'; execute immediate l_sqlstring; end loop; l_plsqlblock := 'begin for l_rec in (select * from execute_table) loop dbms_output.put_line(l_rec.col1); end loop; end;'; execute immediate l_plsqlblock; execute immediate 'drop table execute_table'; end; Webster University Distributed Database Applications Jiangping Wang EXECUTE IMMEDIATE Statement execute immediate 'create index emp_u_1 on employee (last_name)'; create or replace procedure execddl (ddl_string in varchar2) is begin execute immediate ddl_string; end; exec execddl( 'create index emp_u_i on employee(last_name)'); Webster University Distributed Database Applications Jiangping Wang EXECUTE IMMEDIATE Statement CREATE OR REPLACE FUNCTION tabCount ( tab IN VARCHAR2, whr IN VARCHAR2 := NULL, sch IN VARCHAR2 := NULL) RETURN INTEGER IS retval INTEGER; BEGIN EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || NVL (sch, USER) || '.' || tab || ' WHERE ' || NVL (whr, '1=1') INTO retval; RETURN retval; END; / if tabcount ('emp', 'deptno = ' || v_dept) > 100 then dbms_output.put_line('growing fast!'); end if; Webster University Distributed Database Applications Jiangping Wang EXECUTE IMMEDIATE Statement Bind Variable CREATE OR REPLACE FUNCTION updNVal ( tab IN VARCHAR2, col IN VARCHAR2, val IN NUMBER, PL/SQL engine replaces the various whr IN VARCHAR2 := NULL, placeholders with the values in the sch IN VARCHAR2 := NULL) USING clause RETURN PLS_INTEGER IS BEGIN EXECUTE IMMEDIATE 'UPDATE ' || NVL (sch, USER) || '.' || tab || ' SET ' || col || ' = :the_value WHERE ' || NVL (whr, '1=1') USING val; RETURN SQL%ROWCOUNT; END; / Webster University Distributed Database Applications Jiangping Wang EXECUTE IMMEDIATE Statement Bind Variable CREATE OR REPLACE PROCEDURE run_9am_procedure ( id_in IN employee.employee_id%TYPE, hour_in IN INTEGER) IS v_apptcount INTEGER; v_name VARCHAR2 (100); BEGIN EXECUTE IMMEDIATE 'BEGIN ' || TO_CHAR (SYSDATE, 'DAY') || '_set_schedule (:id, :hour, :name, :appts); END;' USING IN id_in, IN hour_in, OUT v_name, OUT v_apptcount; DBMS_OUTPUT.put_line ( 'Employee ' || v_name || ' has ' || v_apptcount || ' appointments on ' || TO_CHAR (SYSDATE)); END; / Webster University Distributed Database Applications Jiangping Wang OPEN FOR Statement Extend cursor variables to support dynamic SQL create or replace procedure show_parts_inventory ( parts_table in varchar2, where_n in varchar2 := null) is type query_curtype is ref cursor; dyncur query_curtype; begin open dyncur for ‘select * from ’ || parts_table ‘where ’ || nvl(where_in, ‘1=1’); … end; Webster University Distributed Database Applications Jiangping Wang OPEN FOR Statement create or replace procedure show_employee ( table_in in varchar2, where_in in varchar2 := null) is type query_curtype is ref cursor; dyncur query_curtype; emp employee%rowtype; begin open dyncur for 'select * from ' || table_in || ' where ' || nvl (where_in, '1=1'); dbms_output.put_line('Employee list:'); loop fetch dyncur into emp; exit when dyncur%notfound; dbms_output.put_line(emp.lname || ' ' || emp.fname); end loop; close dyncur; end; / Webster University Distributed Database Applications Jiangping Wang Multirow Queries with Cursor Variables CREATE OR REPLACE PROCEDURE showcol ( tab IN VARCHAR2, col IN VARCHAR2, whr IN VARCHAR2 := NULL) IS TYPE cv_type IS REF CURSOR; cv cv_type; val VARCHAR2(32767); BEGIN OPEN cv FOR 'SELECT ' || col || ' FROM ' || tab || ' WHERE ' || NVL (whr, '1 = 1'); LOOP FETCH cv INTO val; EXIT WHEN cv%NOTFOUND; IF cv%ROWCOUNT = 1 THEN DBMS_OUTPUT.PUT_LINE (RPAD ('-', 60, '-')); DBMS_OUTPUT.PUT_LINE ('Contents of '||UPPER(tab)||'.'||UPPER(col)); DBMS_OUTPUT.PUT_LINE (RPAD ('-', 60, '-')); END IF; DBMS_OUTPUT.PUT_LINE (val); END LOOP; CLOSE cv; END; / Jiangping Wang Webster University Distributed Database Applications FETCH into Variables Declare type cv_type is ref cursor; cv cv_type; mega_bucks company.ceo_compensation%type; achieved_by company.cost_cutting%type; Begin Open cv for ‘select ceo_compensation, cost_curtting from company where ’ || nvl (whr, ‘1=1’); loop fetch cv into mega_bucks, achieved_by; Webster University Distributed Database Applications Jiangping Wang FETCH into Records Declare type cv_type is ref cursor; cv cv_type; ceo_info company%rowtype; Begin Open cv for ‘select * from from company where ’ || nvl (whr, ‘1=1’); loop fetch cv into ceo_info; Webster University Distributed Database Applications Jiangping Wang FETCH into Records create or replace package company_struc is type dynsql_curtype is ref cursor; type ceo_info_rt is record ( mega_bucks company.ceo_compensation%type, achieved_by company.cost_cutting%type); declare cv company_struc.dynsql_curtype; rec company_struc.ceo_info_rt; begin open cv for ‘select ceo_eompensatin, cost_cutting from company where ’ || nvl (whr, ‘1=1’); loop fetch cv into rec; Webster University Distributed Database Applications Jiangping Wang The USING Clause in OPEN FOR OPEN cv FOR 'SELECT ' || col || ' FROM ' || tab || ' WHERE ' || dtcol || ' BETWEEN TRUNC (:startdt) AND TRUNC (:enddt)' USING dt1, NVL (dt2, dt1+1); LOOP FETCH cv INTO val; EXIT WHEN cv%NOTFOUND; IF cv%ROWCOUNT = 1 THEN … Webster University Distributed Database Applications Jiangping Wang Binding Variables Binding utilizes placeholders and USING clause EXECUTE IMMEDIATE 'UPDATE ' || tab || ' SET sal = :new_sal' USING v_sal; Concatenation adds values directly to the SQL string EXECUTE IMMEDIATE 'UPDATE ' || tab || ' SET sal = ' || v_sal; Binding is faster Binding is easier to write and maintain Binding negates the chance of code injection Webster University Distributed Database Applications Jiangping Wang Code Injection CREATE OR REPLACE PROCEDURE get_rows ( ssn_in in VARCHAR2 ) IS l_where VARCHAR2(32767); BEGIN l_where := 'ssn = ' || ssn_in; EXECUTE IMMEDIATE 'DECLARE l_row employee%ROWTYPE; BEGIN SELECT * INTO l_row FROM employee WHERE ' || l_where || '; dbms_output.put_line(l_row.lname); END;'; END get_rows; / Webster University Distributed Database Applications Jiangping Wang Avoid Code Injection CREATE OR REPLACE PROCEDURE get_rows ( ssn_in in VARCHAR2 ) IS l_where VARCHAR2(32767); BEGIN l_where := 'ssn = :ssnumber'; EXECUTE IMMEDIATE 'DECLARE l_row employee%ROWTYPE; BEGIN SELECT * INTO l_row FROM employee WHERE ' || l_where || '; dbms_output.put_line(l_row.lname); END;' USING ssn_in; END get_rows; / Webster University Distributed Database Applications Jiangping Wang Argument Modes IN, OUT, IN OUT create or replace procedure wrong_incentive( company_in in integer, new_layoffs in number) is sql_string varchar2(2000); sal_after_layoffs number; begin sql_string := ‘update ceo_compensation set salary = salary + 10 * :layoffs where company_id = :company returning salary into :newsal’; execute immediate sql_string using new_layoffs, company_in, out sal_after_layoffs; dbms_output.put_line (ceo compensation after latest round of layoffs $’ || sal_after_layoffs); end; Webster University Distributed Database Applications Jiangping Wang Duplicate Placeholders create or replace procedure updnumval ( Dynamic SQL, supply col_in in varchar2, for each placeholder start_in in date, end_in in date, val_in in number) is dml_str varchar2(32767) := 'update emp set ' || col_in || ' := :val where hiredate between :lodate and :hidate and :val is not null'; begin execute immediate dml_str using val_in, start_in, end_in, val_in; end; an argument create or replace procedure updnumval ( col_in in varchar2, Dynamic PL/SQL block, supply an start_in in date, argument for each unique placeholder end_in in date, val_in in number) is dml_str varchar2(32767) := 'begin update emp set ' || col_in || ' := :val where hiredate between :lodate and :hidate and :val is not null; end; '; begin execute immediate dml_str using val_in, start_in, end_in; end; Webster University Distributed Database Applications Jiangping Wang Dynamic SQL and Static SQL More versatile than plain embedded SQL programs Can be built interactively with input from users having little or no knowledge of SQL For highly flexible applications Require complex coding Use of special data structures More runtime processing Webster University Distributed Database Applications Jiangping Wang Oracle's Object Features Object programming features Creating base type and subtype Creating object Storing, retrieving, and using persistent objects Webster University Distributed Database Applications Jiangping Wang Object Programming Features Webster University Distributed Database Applications Jiangping Wang Object Programming Features Webster University Distributed Database Applications Jiangping Wang Library Catalog Type Hierarchy Webster University Distributed Database Applications Jiangping Wang Creating Base Type CREATE OR REPLACE TYPE catalog_item_t AS OBJECT ( id INTEGER, title VARCHAR2(4000), NOT INSTANTIABLE MEMBER FUNCTION ck_digit_okay RETURN BOOLEAN, MEMBER FUNCTION print RETURN VARCHAR2 ) NOT INSTANTIABLE NOT FINAL; / Webster University Distributed Database Applications Jiangping Wang Creating Subtype CREATE OR REPLACE TYPE book_t UNDER catalog_item_t ( isbn VARCHAR2(13), pages INTEGER, CONSTRUCTOR FUNCTION book_t ( id IN INTEGER DEFAULT NULL, title IN VARCHAR2 DEFAULT NULL, isbn IN VARCHAR2 DEFAULT NULL, pages IN INTEGER DEFAULT NULL) RETURN SELF AS RESULT, OVERRIDING MEMBER FUNCTION ck_digit_okay RETURN BOOLEAN, OVERRIDING MEMBER FUNCTION print RETURN VARCHAR2 ); / Webster University Distributed Database Applications Jiangping Wang Creating Subtype CREATE OR REPLACE TYPE serial_t UNDER catalog_item_t ( issn VARCHAR2(10), open_or_closed VARCHAR2(1), CONSTRUCTOR FUNCTION serial_t ( id IN INTEGER DEFAULT NULL, title IN VARCHAR2 DEFAULT NULL, issn IN VARCHAR2 DEFAULT NULL, open_or_closed IN VARCHAR2 DEFAULT NULL) RETURN SELF AS RESULT, OVERRIDING MEMBER FUNCTION ck_digit_okay RETURN BOOLEAN, OVERRIDING MEMBER FUNCTION print RETURN VARCHAR2 ) NOT FINAL; / Webster University Distributed Database Applications Jiangping Wang Creating Object DECLARE generic_item catalog_item_t; abook book_t; BEGIN abook := NEW book_t(title => 'Out of the Silent Planet', isbn => '0-6848-238-02'); generic_item := abook; DBMS_OUTPUT.PUT_LINE('BOOK: ' || abook.print()); DBMS_OUTPUT.PUT_LINE('ITEM: ' || generic_item.print()); END; Webster University Distributed Database Applications Jiangping Wang Storing Persistent Objects CREATE TABLE catalog_items OF catalog_item_t (CONSTRAINT catalog_items_pk PRIMARY KEY (id)); CREATE TABLE my_writing_projects ( project_id INTEGER NOT NULL PRIMARY KEY, start_date DATE, working_title VARCHAR2(4000), catalog_item catalog_item_t); DESC catalog_items desc my_writing_projects INSERT INTO catalog_items VALUES (NEW book_t(10003, 'Perelandra', '0-684-82382-9', 222)); INSERT INTO catalog_items VALUES (NEW serial_t(10004, 'Time', '0040-781X', 'O')); Webster University Distributed Database Applications Jiangping Wang Retrieving Persistent Objects The VALUE function Accepts a single argument, which must be a table alias in the current FROM clause Returns an object of the type on which the table is defined SELECT VALUE(c) FROM catalog_items c; SELECT VALUE(c).id, VALUE(c).print() FROM catalog_items c; Webster University Distributed Database Applications Jiangping Wang Retrieving Persistent Objects DECLARE catalog_item catalog_item_t; CURSOR ccur IS SELECT VALUE(c) FROM catalog_items c; BEGIN OPEN ccur; FETCH ccur INTO catalog_item; DBMS_OUTPUT.PUT_LINE('I fetched item #' || catalog_item.id); CLOSE ccur; END; Webster University Distributed Database Applications Jiangping Wang Object Downcasting The TREAT function Treat a generic base type object as the more narrowly defined subtype object DECLARE book book_t; catalog_item catalog_item_t := NEW book_t(); BEGIN book := TREAT(catalog_item AS book_t); END; / Webster University Distributed Database Applications Jiangping Wang Test Object Type DECLARE CURSOR ccur IS SELECT VALUE(c) item FROM catalog_items c; arec ccur%ROWTYPE; BEGIN FOR arec IN ccur LOOP CASE WHEN arec.item IS OF (book_t) THEN DBMS_OUTPUT.PUT_LINE('Found a book with ISBN ' || TREAT(arec.item AS book_t).isbn); WHEN arec.item IS OF (serial_t) THEN DBMS_OUTPUT.PUT_LINE('Found a serial with ISSN ' || TREAT(arec.item AS serial_t).issn); ELSE DBMS_OUTPUT.PUT_LINE('Found unknown catalog item'); END CASE; END LOOP; END; Webster University Distributed Database Applications Jiangping Wang Globalization and Localization Unicode support Variable precision Single-byte vs. multi-byte Sorting order Non-character data Date and time Currency Webster University Distributed Database Applications Jiangping Wang Character Codes ASCII The ASCII Character set: characters 32 – 127. Webster University Distributed Database Applications Jiangping Wang ASCII 1967 0 1 2 3 4 5 6 7 8 9 0 NUL SOH STX ETX EOT ENQ ACK BEL BS HT 1 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAL EM 2 sp ! ” # $ % & ’ ( ) 3 0 1 2 3 4 5 6 7 8 9 4 @ A B C D E F G H I A B C D E F LF VT FF CR SO SI SUB ESC FS GS RS US / ? O * : J + ; K , < L = M . > N 5 P Q R S T U V W X Y Z [ \ ] ^ _ 6 7 ` p a q b r c s d t e y f v g w h x i y j z k { l | m } n ~ Webster University Distributed Database Applications o DEL Jiangping Wang ISO 8859-1 0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 sp 3 0 4 @ ! 1 A ” 2 B # 3 C $ 4 D % 5 E & 6 F ’ 7 G ( 8 H ) 9 I * : J + ; K , < L = M . > N / ? O 5 Q R S T U V W X Y Z [ \ ] ^ _ 6 ` a b 7 p q r 8 9 A NBSP ¡ ¢ B ° ± ² C À Á Â D Ð Ñ Ò E à á â F ð ñ ò Webster University c s d t e y f v g w h x i y j z k { l | m } n ~ £ ³ Ã Ó ã ó ¤ ¥ ¦ § ¨ © ª ´ µ ¶ · ¸ ¹ º Ä Å Æ Ç È É Ê Ô Õ Ö × Ø Ù Ú ä å æ ç è é ê ô Distributed õ ö Database ÷ Applications ø ù ú « » Ë Û ë û ¬ ¼ Ì Ü ì ü ½ Í Ý í ý ® ¯ ¾ ¿ Î Ï Þ ß î ï þ Jiangping ÿ Wang P o DEL Unicode Support Unicode is a standard for representing characters Character encoding with UTF UTF-8 UTF-16 UTF-32 Webster University Distributed Database Applications Jiangping Wang Unicode Encoding Space F, 10: Private Use Planes E: Supplementary Special-Purpose Pla Unassigned 2: Supplementary Ideographic Plane 1: Supplementary Multilingual Plane 0: Basic Multilingual Plane Webster University Distributed Database Applications Jiangping Wang Encoding Characters Associating characters with values in the code space Webster University Distributed Database Applications Jiangping Wang Encoding Forms Three equivalent and interconvertible binary representations Webster University Distributed Database Applications Jiangping Wang Oracle Character Sets Character set NLS_CHARACTERSET NLS_NCHAR_CHARACTERSET Data types CHAR and VARCHAR NCHAR and NVARCHAR Webster University Fixed-length Variable-length Database character set CHAR VARCHAR2 National character set NCHAR NVARCHAR2 Distributed Database Applications Jiangping Wang Oracle Character Sets Webster University Distributed Database Applications Jiangping Wang Unicode Support Webster University Distributed Database Applications Jiangping Wang