PL/ SQL homework question.

I turn here because I have a bad teacher and I don't want to drop her course but I need help with trying to get a procedure to work. Be patient I will post the assignment first. Then I will post the code I created and the subsequent error that I get. Your help would be greatly appreciated. WARNING: It will be a long post.
Assignment:
The company wants to offer an incentive of free shipping to those customers who have not returned for two months. Create a procedure named PROMO_SHIP_SP that determines who these customers are and then updates the BB_PROMOLIST table accordingly. The procedure uses the following information:
1. Date cutoff = Any customers who have not shopped on the site since this date should be included as incentive participants. use the basket created date to reflect shopper activity dates.
2.) Month = Three-Character month (Such as APR) that should be added to the promotion table to indicate which month the free shipping is available.
3.) Year = Four digit year indicating the year the promotion is effective.
4.) PROMO_FLAG = 1 (representing free shipping).
The BB_PROMOLIST table also has a USED column, which contains a default value of 'N' and is updated to a 'Y' when the shopper uses the promotion. Test the procedure with a cutoff date of 15-FEB-03. Assign the free shipping for the month of APR and the year 2003.
Here is what I wrote based on the instructions:
create or replace procedure promo_ship1_sp
(--p_day in DATE,
p_mth in DATE,
p_yr in DATE)
IS
CURSOR cur_ship IS
SELECT idshopper, MAX(dtcreated) dt
from bb_basket
WHERE dtcreated < '15-FEB-03' -- AND
-- TO_CHAR(dtCreated, 'DD') = p_day
AND TO_CHAR(dtCreated, 'MON') = p_mth
AND TO_CHAR(dtcreated, 'YY') = p_yr
and orderplaced = 1
group by dtcreated;
promo_flag number; --(1);
v_cutoff DATE;
BEGIN
FOR rec_ship in cur_ship LOOP
IF rec_ship.dt < v_cutoff then
promo_flag := 1;
--END IF;
v_cutoff := to_char('15-FEB-03');
ELSIF rec_ship.dt > v_cutoff then
DBMS_OUTPUT.PUT_LINE('Dont qualify for shipping.');
END IF;
DBMS_OUTPUT.PUT_LINE(rec_ship.idshopper||' cart creation = '|| rec_ship.dt ||'
flag status = '|| promo_flag);
/* IF promo_flag IS NOT NULL THEN
insert into bb_promolist
VALUES (rec_ship.idshopper, p_mth, p_year, promo_flag, 'Y', 'APR-03');
-- END IF;
promo_flag := NULL; */
END LOOP;
--commit;
END;
ERROR I get from execution:
Procedure created.
SQL> execute promo_ship1_sp('FEB', '03');
BEGIN promo_ship1_sp('FEB', '03'); END;
ERROR at line 1:
ORA-01858: a non-numeric character was found where a numeric was expected
ORA-06512: at line 1
SQL> execute promo_ship1_sp('03', 'FEB');
BEGIN promo_ship1_sp('03', 'FEB'); END;
ERROR at line 1:
ORA-01840: input value not long enough for date format
ORA-06512: at line 1
SQL> execute promo_ship1_sp('2003', 'FEB');
BEGIN promo_ship1_sp('2003', 'FEB'); END;
ERROR at line 1:
ORA-01861: literal does not match format string
ORA-06512: at line 1

The best advice we can give you is to do the simplest thing that could work. Quite often that is the best solution. One trap beginners often fall into is overcomplicating things. As it stands, the requirements you have been given can be met by a simple SQL INSERT statement driving off a subquery on the basket table.
I will post a solution: it's up to you to decide whether you want to look at it or figure it out for yourself ;)
This code has not been tested as you haven't given us the structure of the underlying tables, so you may need to debug it.
Cheers, APC
#    solution -------+
#                    |                
#                    |  
#                    |  
#                    |  
#                   \|/  
create or replace procedure promo_ship_sp
     (p_cutoff in DATE
       , p_mth in varchar2
       , p_yr in varchar2
       , p_promo_flag number: =1)
is
begin
     insert into bb_promolist
     select distinct idshopper
          , p_mth
          , p_year
          , p_promo_flag
          , 'N'
     from bb_basket
     where dtcreated <= p_cutoff
     and orderplaced = 1;
end promo_ship_sp;     
/

Similar Messages

  • NEED HELP IN SQL HOMEWORK PROBLEMS

    I NEED HELP IN MY SQL HOMEWORK PROBLEMS....
    I CAN SEND IT VIA EMAIL ATTACHMENT IN MSWORD....

    Try this:
    SELECT SUBSTR( TN,
                   DECODE(LEVEL, 1, 1, INSTR(TN, '#', 1, LEVEL-1) + 1),
                   DECODE( INSTR(TN, '#', 1, LEVEL) , 0 ,
                           LENGTH(TN) + 1, INSTR(TN, '#', 1, LEVEL) )
                   - DECODE(LEVEL, 1, 1, INSTR(TN, '#', 1, LEVEL-1 ) + 1)
           ) xxx
    FROM (
        SELECT '234123#1254343#909823#908232#12345' TN FROM DUAL
    CONNECT BY LEVEL <= LENGTH(TN) - LENGTH(REPLACE(TN,'#')) + 1
    XXX                               
    234123                            
    1254343                           
    909823                            
    908232                            
    12345
    SELECT regexp_substr(tn, '[^#]+', 1, level) xx
    FROM (
        SELECT '234123#1254343#909823#908232#12345' TN FROM DUAL
    CONNECT BY LEVEL <= LENGTH(TN) - LENGTH(REPLACE(TN,'#')) + 1
    XX                                
    234123                            
    1254343                           
    909823                            
    908232                            
    12345 

  • Oracle SQL and PL/SQL interview questions.

    Can anyone forward me all Oracle SQL and PL/SQL Interview questions and answers asap.
    Many Thanks.
    Bba

    Dear Pal
    I not sure all the all answers are correct. I got one mail couple yrs back. I am just sharing mail contents. Kindly keep question and compare answers.
    1 Which is more faster - IN or EXISTS?
    EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN returns a value.
    2 Which datatype is used for storing graphics and images?
    LONG RAW data type is used for storing BLOB's (binary large objects).
    3 When do you use WHERE clause and when do you use HAVING clause?
    HAVING clause is used when you want to specify a condition for a group function and it is written after GROUP BY clause. The WHERE clause is used when you want to specify a condition for columns, single row functions except group functions and it is written before GROUP BY clause if it is used.
    4 What WHERE CURRENT OF clause does in a cursor?
    LOOPSELECT num_credits INTO v_numcredits FROM classesWHERE dept=123 and course=101;UPDATE studentsSET current_credits=current_credits+v_numcreditsWHERE CURRENT OF X;END LOOPCOMMIT;END;
    5 What should be the return type for a cursor variable.Can we use a scalar data type as return type?
    The return type for a cursor must be a record type.It can be declared explicitly as a user-defined or %ROWTYPE can be used. eg TYPE t_studentsref IS REF CURSOR RETURN students%ROWTYPE
    6 What is use of a cursor variable? How it is defined?
    A cursor variable is associated with different statements at run time, which can hold different values at run time. Static cursors can only be associated with one run time query. A cursor variable is reference type (like a pointer in C).Declaring a cursor variable:TYPE type_name IS REF CURSOR RETURN return_type type_name is the name of the reference type,return_type is a record type indicating the types of the select list that will eventually be returned by the cursor variable.
    7 What is the purpose of a cluster?
    Oracle does not allow a user to specifically locate tables, since that is a part of the function of the RDBMS. However, for the purpose of increasing performance, oracle allows a developer to create a CLUSTER. A CLUSTER provides a means for storing data from different tables together for faster retrieval than if the table placement were left to the RDBMS.
    8 What is the maximum buffer size that can be specified using the DBMS_OUTPUT.ENABLE function?
    1,000,00
    9 What is syntax for dropping a procedure and a function .Are these operations possible?
    Drop Procedure procedure_nameDrop Function function_name
    10 What is OCI. What are its uses?
    Oracle Call Interface is a method of accesing database from a 3GL program. Uses--No precompiler is required,PL/SQL blocks are executed like other DML statements. The OCI library provides· -functions to parse SQL statemets· -bind input variables· -bind output variables· -execute statements· -fetch the results
    11 What is difference between UNIQUE and PRIMARY KEY constraints?
    A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys. The columns that compose PK are automatically define NOT NULL, whereas a column that compose a UNIQUE is not automatically defined to be mandatory must also specify the column is NOT NULL.
    12 What is difference between SUBSTR and INSTR?
    SUBSTR returns a specified portion of a string eg SUBSTR('BCDEF',4) output BCDEINSTR provides character position in which a pattern is found in a string. eg INSTR('ABC-DC-F','-',2) output 7 (2nd occurence of '-')
    13 What is difference between SQL and SQL*PLUS?
    SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool. Its a command line tool that allows user to type SQL commands to be executed directly against an Oracle database. SQL is a language used to query the relational database(DML,DCL,DDL). SQL*PLUS commands are used to format query result, Set options, Edit SQL commands and PL/SQL.
    14 What is difference between Rename and Alias?
    Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or column which do not exist once the SQL statement is executed.
    15 What is difference between a formal and an actual parameter?
    The variables declared in the procedure and which are passed, as arguments are called actual, the parameters in the procedure declaration. Actual parameters contain the values that are passed to a procedure and receive results. Formal parameters are the placeholders for the values of actual parameters
    16 What is an UTL_FILE.What are different procedures and functions associated with it?
    UTL_FILE is a package that adds the ability to read and write to operating system files. Procedures associated with it are FCLOSE, FCLOSE_ALL and 5 procedures to output data to a file PUT, PUT_LINE, NEW_LINE, PUTF, FFLUSH.PUT, FFLUSH.PUT_LINE,FFLUSH.NEW_LINE. Functions associated with it are FOPEN, ISOPEN.
    17 What is a view ?
    A view is stored procedure based on one or more tables, it’s a virtual table.
    18 What is a pseudo column. Give some examples?
    It is a column that is not an actual column in the table.eg USER, UID, SYSDATE, ROWNUM, ROWID, NULL, AND LEVEL.
    19 What is a OUTER JOIN?
    Outer Join--Its a join condition used where you can query all the rows of one of the tables in the join condition even though they don’t satisfy the join condition.
    20 What is a cursor?
    Oracle uses work area to execute SQL statements and store processing information PL/SQL construct called a cursor lets you name a work area and access its stored information A cursor is a mechanism used to fetch more than one row in a Pl/SQl block.
    21 What is a cursor for loop?
    Cursor For Loop is a loop where oracle implicitly declares a loop variable, the loop index that of the same record type as the cursor's record.
    22 What are various privileges that a user can grant to another user?
    · SELECT· CONNECT· RESOURCES
    23 What are various constraints used in SQL?
    · NULL· NOT NULL· CHECK· DEFAULT
    24 What are ORACLE PRECOMPILERS?
    Using ORACLE PRECOMPILERS, SQL statements and PL/SQL blocks can be contained inside 3GL programs written in C,C++,COBOL,PASCAL, FORTRAN,PL/1 AND ADA.The Precompilers are known as Pro*C,Pro*Cobol,...This form of PL/SQL is known as embedded pl/sql,the language in which pl/sql is embedded is known as the host language. The prcompiler translates the embedded SQL and pl/sql ststements into calls to the precompiler runtime library.The output must be compiled and linked with this library to creater an executable.
    25 What are different Oracle database objects?
    · TABLES· VIEWS· INDEXES· SYNONYMS· SEQUENCES· TABLESPACES etc
    26 What are different modes of parameters used in functions and procedures?
    · IN· OUT· INOUT
    27 What are cursor attributes?
    · %ROWCOUNT· %NOTFOUND· %FOUND· %ISOPEN
    28 What a SELECT FOR UPDATE cursor represent. [ANSWER]SELECT......FROM......FOR......UPDATE[OF column-reference][NOWAIT] The processing done in a fetch loop modifies the rows that have been retrieved by the cursor. A convenient way of modifying the rows is done by a method with two parts: the FOR UPDATE clause in the cursor declaration, WHERE CURRENT OF CLAUSE in an UPDATE or declaration statement.
    29 There is a string 120000 12 0 .125 , how you will find the position of the decimal place?
    INSTR('120000 12 0 .125',1,'.')output 13
    30 There is a % sign in one field of a column. What will be the query to find it?
    '' Should be used before '%'.
    31 Suppose a customer table is having different columns like customer no, payments.What will be the query to select top three max payments?
    SELECT customer_no, payments from customer C1
    WHERE 3<=(SELECT COUNT(*) from customer C2
    WHERE C1.payment <= C2.payment)
    32 minvalue.sql Select the Nth lowest value from a table
    select level, min('col_name') from my_table where level = '&n' connect by prior ('col_name') <
    'col_name')
    group by level;
    Example:
    Given a table called emp with the following columns:
    -- id number
    -- name varchar2(20)
    -- sal number
    -- For the second lowest salary:
    -- select level, min(sal) from emp
    -- where level=2
    -- connect by prior sal < sal
    -- group by level
    33 maxvalue.sql Select the Nth Highest value from a table
    select level, max('col_name') from my_table where level = '&n' connect by prior ('col_name') >
    'col_name')
    group by level;
    Example:
    Given a table called emp with the following columns:
    -- id number
    -- name varchar2(20)
    -- sal number
    -- For the second highest salary:
    -- select level, max(sal) from emp
    -- where level=2
    -- connect by prior sal > sal
    -- group by level
    34 How you will avoid your query from using indexes?
    SELECT * FROM emp
    Where emp_no+' '=12345;
    i.e you have to concatenate the column name with space within codes in the where condition.
    SELECT /*+ FULL(a) */ ename, emp_no from emp
    where emp_no=1234;
    i.e using HINTS
    35 How you will avoid duplicating records in a query?
    By using DISTINCT
    36 How you were passing cursor variables in PL/SQL 2.2?
    In PL/SQL 2.2 cursor variables cannot be declared in a package.This is because the storage for a cursor variable has to be allocated using Pro*C or OCI with version 2.2, the only means of passing a cursor variable to a PL/SQL block is via bind variable or a procedure parameter.
    37 How you open and close a cursor variable.Why it is required?
    OPEN cursor variable FOR SELECT...Statement
    CLOSE cursor variable In order to associate a cursor variable with a particular SELECT statement OPEN syntax is used. In order to free the resources used for the query CLOSE statement is used.
    38 How will you delete duplicating rows from a base table?
    delete from table_name where rowid not in (select max(rowid) from table group by duplicate_values_field_name); or
    delete duplicate_values_field_name dv from table_name ta where rowid <(select min(rowid) from table_name tb where ta.dv=tb.dv);
    39 How do you find the numbert of rows in a Table ?
    A bad answer is count them (SELECT COUNT(*) FROM table_name)
    A good answer is :-
    'By generating SQL to ANALYZE TABLE table_name COUNT STATISTICS by querying Oracle System Catalogues (e.g. USER_TABLES or ALL_TABLES).
    The best answer is to refer to the utility which Oracle released which makes it unnecessary to do ANALYZE TABLE for each Table individually.
    40 Find out nth highest salary from emp table
    SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B WHERE a.sal<=b.sal);
    For Eg:-
    Enter value for n: 2
    SAL
    3700
    41 Display the records between two range?
    select rownum, empno, ename from emp where rowid in (select rowid from emp where rownum <=&upto minus select rowid from emp where rownum<&Start);
    42 Display the number value in Words?
    SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))
    from emp;
    the output like,
    SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
    800 eight hundred
    1600 one thousand six hundred
    1250 one thousand two hundred fifty
    If you want to add some text like, Rs. Three Thousand only.
    SQL> select sal "Salary ",
    (' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))
    "Sal in Words" from emp
    Salary Sal in Words
    800 Rs. Eight Hundred only.
    1600 Rs. One Thousand Six Hundred only.
    1250 Rs. One Thousand Two Hundred Fifty only.
    43 Display Odd/ Even number of records
    Odd number of records:
    select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
    Output:-
    1
    3
    5
    Even number of records:
    select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
    Output:-
    2
    4
    6
    44 Difference between procedure and function.
    Functions are named PL/SQL blocks that return a value and can be called with arguments procedure a named block that can be called with parameter. A procedure all is a PL/SQL statement by itself, while a Function call is called as part of an expression.
    45 Difference between NO DATA FOUND and %NOTFOUND
    NO DATA FOUND is an exception raised only for the SELECT....INTO statements when the where clause of the querydoes not match any rows. When the where clause of the explicit cursor does not match any rows the %NOTFOUND attribute is set to TRUE instead.
    46 Difference between database triggers and form triggers?
    Data base trigger(DBT) fires when a DML operation is performed on a data base table. Form trigger(FT) Fires when user presses a key or navigates between fields on the screen
    Can be row level or statement level No distinction between row level and statement level.
    Can manipulate data stored in Oracle tables via SQL Can manipulate data in Oracle tables as well as variables in forms.
    Can be fired from any session executing the triggering DML statements. Can be fired only from the form that define the trigger.
    Can cause other database triggers to fire.Can cause other database triggers to fire, but not other form triggers.
    47 Difference between an implicit & an explicit cursor.
    PL/SQL declares a cursor implicitly for all SQL data manipulation statements, including quries that return only one row. However,queries that return more than one row you must declare an explicit cursor or use a cursor FOR loop.
    Explicit cursor is a cursor in which the cursor name is explicitly assigned to a SELECT statement via the CURSOR...IS statement. An implicit cursor is used for all SQL statements Declare, Open, Fetch, Close. An explicit cursors are used to process multirow SELECT statements An implicit cursor is used to process INSERT, UPDATE, DELETE and single row SELECT. .INTO statements.
    48 Can you use a commit statement within a database trigger?
    No.
    49 Can the default values be assigned to actual parameters?
    Yes
    50 Can cursor variables be stored in PL/SQL tables.If yes how. If not why?
    No, a cursor variable points a row which cannot be stored in a two-dimensional PL/SQL table.
    51 Can a primary key contain more than one columns?
    Yes
    52 Can a function take OUT parameters. If not why?
    No. A function has to return a value,an OUT parameter cannot return a value.
    53 What are various joins used while writing SUBQUERIES?
    Self join-Its a join foreign key of a table references the same table. Outer Join--Its a join condition used where One can query all the rows of one of the tables in the join condition even though they don't satisfy the join condition.
    Equi-join--Its a join condition that retrieves rows from one or more tables in which one or more columns in one table are equal to one or more columns in the second table.
    54 Differentiate between TRUNCATE and DELETE
    TRUNCATE deletes much faster than DELETE
    TRUNCATE
    DELETE
    It is a DDL statement It is a DML statement
    It is a one way trip,cannot ROLLBACK One can Rollback
    Doesn't have selective features (where clause) Has
    Doesn't fire database triggers Does
    It requires disabling of referential constraints. Does not require
    1 What is PL/SQL ?
    PL/SQL is a procedural language that has both interactive SQL and procedural programming language constructs such as iteration, conditional branching.
    2 Write the order of precedence for validation of a column in a table ?
    I. done using Database triggers.
    ii. done using Integarity Constraints.
    I & ii.
    Exception :
    3 Where the Pre_defined_exceptions are stored ?
    In the standard package.
    Procedures, Functions & Packages ;
    4 What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?
    % TYPE provides the data type of a variable or a database column to that variable.
    % ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor.
    The advantages are : I. Need not know about variable's data type
    ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly.
    5 What will happen after commit statement ?
    Cursor C1 is
    Select empno,
    ename from emp;
    Begin
    open C1; loop
    Fetch C1 into
    eno.ename;
    Exit When
    C1 %notfound;-----
    commit;
    end loop;
    end;
    The cursor having query as SELECT .... FOR UPDATE gets closed after COMMIT/ROLLBACK.
    The cursor having query as SELECT.... does not get closed even after COMMIT/ROLLBACK.
    6 What is the basic structure of PL/SQL ?
    PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be used in PL/SQL.
    7 What is Raise_application_error ?
    Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an user_defined error messages from stored sub-program or database trigger.
    8 What is Pragma EXECPTION_INIT ? Explain the usage ?
    The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error. To get an error message of a specific oracle error.
    e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)
    9 What is PL/SQL table ?
    Objects of type TABLE are called "PL/SQL tables", which are modeled as (but not the same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one column and a primary key.
    Cursors
    10 What is Overloading of procedures ?
    The Same procedure name is repeated with parameters of different datatypes and parameters in different positions, varying number of parameters is called overloading of procedures.
    e.g. DBMS_OUTPUT put_line
    What is a package ? What are the advantages of packages ?
    11 What is difference between a PROCEDURE & FUNCTION ?
    A FUNCTION is always returns a value using the return statement.
    A PROCEDURE may return one or more values through parameters or may not return at all.
    12 What is difference between a Cursor declared in a procedure and Cursor declared in a package specification ?
    A cursor declared in a package specification is global and can be accessed by other procedures or procedures in a package.
    A cursor declared in a procedure is local to the procedure that can not be accessed by other procedures.
    13 What is difference between % ROWTYPE and TYPE RECORD ?
    % ROWTYPE is to be used whenever query returns a entire row of a table or view.
    TYPE rec RECORD is to be used whenever query returns columns of different
    table or views and variables.
    E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type
    e_rec emp% ROWTYPE
    cursor c1 is select empno,deptno from emp;
    e_rec c1 %ROWTYPE.
    14 What is an Exception ? What are types of Exception ?
    Exception is the error handling part of PL/SQL block. The types are Predefined and user defined. Some of Predefined exceptions are.
    CURSOR_ALREADY_OPEN
    DUP_VAL_ON_INDEX
    NO_DATA_FOUND
    TOO_MANY_ROWS
    INVALID_CURSOR
    INVALID_NUMBER
    LOGON_DENIED
    NOT_LOGGED_ON
    PROGRAM-ERROR
    STORAGE_ERROR
    TIMEOUT_ON_RESOURCE
    VALUE_ERROR
    ZERO_DIVIDE
    OTHERS.
    15 What is a stored procedure ?
    A stored procedure is a sequence of statements that perform specific function.
    16 What is a database trigger ? Name some usages of database trigger ?
    Database trigger is stored PL/SQL program unit associated with a specific database table. Usages are Audit data modifications, Log events transparently, Enforce complex business rules Derive column values automatically, Implement complex security authorizations. Maintain replicate tables.
    17 What is a cursor for loop ?
    Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of values from active set into fields in the record and closes
    when all the records have been processed.
    eg. FOR emp_rec IN C1 LOOP
    salary_total := salary_total +emp_rec sal;
    END LOOP;
    18 What is a cursor ? Why Cursor is required ?
    Cursor is a named private SQL area from where information can be accessed. Cursors are required to process rows individually for queries returning multiple rows.
    19 What happens if a procedure that updates a column of table X is called in a database trigger of the same table ?
    Mutation of table occurs.
    20 What are two virtual tables available during database trigger execution ?
    The table columns are referred as OLD.column_name and NEW.column_name.
    For triggers related to INSERT only NEW.column_name values only available.
    For triggers related to UPDATE only OLD.column_name NEW.column_name values only available.
    For triggers related to DELETE only OLD.column_name values only available.
    21 What are two parts of package ?
    The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.
    Package Specification contains declarations that are global to the packages and local to the schema.
    Package Body contains actual procedures and local declaration of the procedures and cursor declarations.
    22 What are the two parts of a procedure ?
    Procedure Specification and Procedure Body.
    23 What are the return values of functions SQLCODE and SQLERRM ?
    SQLCODE returns the latest code of the error that has occurred.
    SQLERRM returns the relevant error message of the SQLCODE.
    24 What are the PL/SQL Statements used in cursor processing ?
    DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types, CLOSE cursor name.
    25 What are the modes of parameters that can be passed to a procedure ?
    IN,OUT,IN-OUT parameters.
    26 What are the datatypes a available in PL/SQL ?
    Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN.
    Some composite data types such as RECORD & TABLE.
    27 What are the cursor attributes used in PL/SQL ?
    %ISOPEN - to check whether cursor is open or not
    % ROWCOUNT - number of rows fetched/updated/deleted.
    % FOUND - to check whether cursor has fetched any row. True if rows are fetched.
    % NOT FOUND - to check whether cursor has fetched any row. True if no rows are featched.
    These attributes are proceeded with SQL for Implicit Cursors and with Cursor name for Explicit Cursors.
    28 What are the components of a PL/SQL Block ?
    Declarative part, Executable part and Exception part.
    Datatypes PL/SQL
    29 What are the components of a PL/SQL block ?
    A set of related declarations and procedural statements is called block.
    30 What are advantages fo Stored Procedures /
    Extensibility,Modularity, Reusability, Maintainability and one time compilation.
    1 What is PL/SQL ?
    PL/SQL is a procedural language that has both interactive SQL and procedural programming language constructs such as iteration, conditional branching.
    2 Write the order of precedence for validation of a column in a table ?
    I. done using Database triggers.
    ii. done using Integarity Constraints.
    I & ii.
    Exception :
    3 Where the Pre_defined_exceptions are stored ?
    In the standard package.
    Procedures, Functions & Packages ;
    4 What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?
    % TYPE provides the data type of a variable or a database column to that variable.
    % ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor.
    The advantages are : I. Need not know about variable's data type
    ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly.
    5 What will happen after commit statement ?
    Cursor C1 is
    Select empno,
    ename from emp;
    Begin
    open C1; loop
    Fetch C1 into
    eno.ename;
    Exit When
    C1 %notfound;-----
    commit;
    end loop;
    end;
    The cursor having query as SELECT .... FOR UPDATE gets closed after COMMIT/ROLLBACK.
    The cursor having query as SELECT.... does not get closed even after COMMIT/ROLLBACK.
    6 What is the basic structure of PL/SQL ?
    PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be used in PL/SQL.
    7 What is Raise_application_error ?
    Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an user_defined error messages from stored sub-program or database trigger.
    8 What is Pragma EXECPTION_INIT ? Explain the usage ?
    The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error. To get an error message of a specific oracle error.
    e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)
    9 What is PL/SQL table ?
    Objects of type TABLE are called "PL/SQL tables", which are modeled as (but not the same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one column and a primary key.
    Cursors
    10 What is Overloading of procedures ?
    The Same procedure name is repeated with parameters of different datatypes and parameters in different positions, varying number of parameters is called overloading of procedures.
    e.g. DBMS_OUTPUT put_line
    What is a package ? What are the advantages of packages ?
    11 What is difference between a PROCEDURE & FUNCTION ?
    A FUNCTION is always returns a value using the return statement.
    A PROCEDURE may return one or more values through parameters or may not return at all.
    12 What is difference between a Cursor declared in a procedure and Cursor declared in a package specification ?
    A cursor declared in a package specification is global and can be accessed by other procedures or procedures in a package.
    A cursor declared in a procedure is local to the procedure that can not be accessed by other procedures.
    13 What is difference between % ROWTYPE and TYPE RECORD ?
    % ROWTYPE is to be used whenever query returns a entire row of a table or view.
    TYPE rec RECORD is to be used whenever query returns columns of different
    table or views and variables.
    E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type
    e_rec emp% ROWTYPE
    cursor c1 is select empno,deptno from emp;
    e_rec c1 %ROWTYPE.
    14 What is an Exception ? What are types of Exception ?
    Exception is the error handling part of PL/SQL block. The types are Predefined and user defined. Some of Predefined exceptions are.
    CURSOR_ALREADY_OPEN
    DUP_VAL_ON_INDEX
    NO_DATA_FOUND
    TOO_MANY_ROWS
    INVALID_CURSOR
    INVALID_NUMBER
    LOGON_DENIED
    NOT_LOGGED_ON
    PROGRAM-ERROR
    STORAGE_ERROR
    TIMEOUT_ON_RESOURCE
    VALUE_ERROR
    ZERO_DIVIDE
    OTHERS.
    15 What is a stored procedure ?
    A stored procedure is a sequence of statements that perform specific function.
    16 What is a database trigger ? Name some usages of database trigger ?
    Database trigger is stored PL/SQL program unit associated with a specific database table. Usages are Audit data modifications, Log events transparently, Enforce complex business rules Derive column values automatically, Implement complex security authorizations. Maintain replicate tables.
    17 What is a cursor for loop ?
    Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of values from active set into fields in the record and closes
    when all the records have been processed.
    eg. FOR emp_rec IN C1 LOOP
    salary_total := salary_total +emp_rec sal;
    END LOOP;
    18 What is a cursor ? Why Cursor is required ?
    Cursor is a named private SQL area from where information can be accessed. Cursors are required to process rows individually for queries returning multiple rows.
    19 What happens if a procedure that updates a column of table X is called in a database trigger of the same table ?
    Mutation of table occurs.
    20 What are two virtual tables available during database trigger execution ?
    The table columns are referred as OLD.column_name and NEW.column_name.
    For triggers related to INSERT only NEW.column_name values only available.
    For triggers related to UPDATE only OLD.column_name NEW.column_name values only available.
    For triggers related to DELETE only OLD.column_name values only available.
    21 What are two parts of package ?
    The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.
    Package Specification contains declarations that are global to the packages and local to the schema.
    Package Body contains actual procedures and local declaration of the procedures and cursor declarations.
    22 What are the two parts of a procedure ?
    Procedure Specification and Procedure Body.
    23 What are the return values of functions SQLCODE and SQLERRM ?
    SQLCODE returns the latest code of the error that has occurred.
    SQLERRM returns the relevant error message of the SQLCODE.
    24 What are the PL/SQL Statements used in cursor processing ?
    DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types, CLOSE cursor name.
    25 What are the modes of parameters that can be passed to a procedure ?
    IN,OUT,IN-OUT parameters.
    26 What are the datatypes a available in PL/SQL ?
    Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN.
    Some composite data types such as RECORD & TABLE.
    27 What are the cursor attributes used in PL/SQL ?
    %ISOPEN - to check whether cursor is open or not
    % ROWCOUNT - number of rows fetched/updated/deleted.
    % FOUND - to check whether cursor has fetched any row. True if rows are fetched.
    % NOT FOUND - to check whether cursor has fetched any row. True if no rows are featched.
    These attributes are proceeded with SQL for Implicit Cursors and with Cursor name for Explicit Cursors.
    28 What are the components of a PL/SQL Block ?
    Declarative part, Executable part and Exception part.
    Datatypes PL/SQL
    29 What are the components of a PL/SQL block ?
    A set of related declarations and procedural statements is called block.
    30 What are advantages fo Stored Procedures /
    Extensibility,Modularity, Reusability, Maintainability and one time compilation.
    31 Name the tables where characteristics of Package, procedure and functions are stored ?
    User_objects, User_Source and User_error.
    32 Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger ? Why ?
    It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in a trigger, it affects logical transaction processing.
    33 How packaged procedures and functions are called from the following?
    a. Stored procedure or anonymous block
    b. an application program such a PRC C, PRO COBOL
    c. SQL *PLUS
    a. PACKAGE NAME.PROCEDURE NAME (parameters);
    variable := PACKAGE NAME.FUNCTION NAME (arguments);
    EXEC SQL EXECUTE
    b.
    BEGIN
    PACKAGE NAME.PROCEDURE NAME (parameters)
    variable := PACKAGE NAME.FUNCTION NAME (arguments);
    END;
    END EXEC;
    c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any
    out/in-out parameters. A function can not be called.
    34 How many types of database triggers can be specified on a table ? What are they ?
    Insert Update Delete
    Before Row o.k. o.k. o.k.
    After Row o.k. o.k. o.k.
    Before Statement o.k. o.k. o.k.
    After Statement o.k. o.k. o.k.
    If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement.
    If WHEN clause is specified, the trigger fires according to the returned Boolean value.
    35 Give the structure of the procedure ?
    PROCEDURE name (parameter list.....)
    is
    local variable declarations
    BEGIN
    Executable statements.
    Exception.
    exception handlers
    end;
    36 Give the structure of the function ?
    FUNCTION name (argument list .....) Return datatype is
    local variable declarations
    Begin
    executable statements
    Exception
    execution handlers
    End;
    37 Explain the usage of WHERE CURRENT OF clause in cursors ?
    WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest row fetched from a cursor.
    Database Triggers
    38 Explain the two type of Cursors ?
    There are two types of cursors, Implicit Cursor and Explicit Cursor.
    PL/SQL uses Implicit Cursors for queries.
    User defined cursors are called Explicit Cursors. They can be declared and used.
    39 Explain how procedures and functions are called in a PL/SQL block ?
    Function is called as part of an expression.
    sal := calculate_sal ('a822');
    procedure is called as a PL/SQL statement
    calculate_bonus ('A822');
    Programmatic Constructs
    Last Update: September 06, 2004
    1 What are the different types of PL/SQL program units that can be defined and stored in ORACLE database ?
    Procedures and Functions,Packages and Database Triggers.
    2 What are the differences between Database Trigger and Integrity constraints ?
    A declarative integrity constraint is a statement about the database that is always true. A constraint applies to existing data in the table and any statement that manipulates the table.
    A trigger does not apply to data loaded before the definition of the trigger, therefore, it does not guarantee all data in a table conforms to the rules established by an associated trigger.
    A trigger can be used to enforce transitional constraints where as a declarative integrity constraint cannot be used.
    3 What is difference between Procedures and Functions ?
    A Function returns a value to the caller where as a Procedure does not.
    4 What is Database Trigger ?
    A Database Trigger is procedure (set of SQL and PL/SQL statements) that is automatically executed as a result of an insert in,update to, or delete from a table.
    5 What is a Procedure ?
    A Procedure consist of a set of SQL and PL/SQL statements that are grouped together as a unit to solve a specific problem or perform a set of related tasks.
    6 What is a Package ?
    A Package is a collection of related procedures, functions, variables and other package constructs together as a unit in the database.
    7 What are the uses of Database Trigger ?
    Database triggers can be used to automatic data generation, audit data modifications, enforce complex Integrity constraints, and customize complex security authorizations.
    8 What are the advantages of having a Package ?
    Increased functionality (for example,global package variables can be declared and used by any proecdure in the package) and performance (for example all objects of the package are parsed compiled, and loaded into memory once)
    1 With which function of summary item is the compute at options required?
    percentage of total functions.
    2 Why is it preferable to create a fewer no. of queries in the data model?
    Because for each query, report has to open a separate cursor and has to rebind, execute and fetch data.
    3 Why is a Where clause faster than a group filter or a format trigger?
    Because, in a where clause the condition is applied during data retrieval than after retrieving the data.
    4 Which parameter can be used to set read level consistency across multiple queries?
    Read only.
    5 Which of the two views should objects according to possession?
    view by structure.
    6 Which of the above methods is the faster method?
    performing the calculation in the query is faster.
    7 Where is the external query executed at the client or the server?
    At the server.
    8 Where is a procedure return in an external pl/sql library executed at the client or at the server?
    At the client.
    9 When do you use data parameter type?
    When the value of a data parameter being passed to a called product is always the name of the record group defined in the current form. Data parameters are used to pass data to produts invoked with the run_product built-in subprogram.
    10 When a form is invoked with call_form, Does oracle forms issues a save point?
    Yes
    11 What are the important difference between property clause and visual attributes?
    Named visual attributes differ only font, color & pattern attributes, property clauses can contain this and any other properties. You can change the appearance of objects at run time by changing the named visual attributes programmatically , property clause assignments cannot be changed programmatically. When an object is inheriting from both a property clause and named visual attribute, the named visual attribute settings take precedence, and any visual attribute properties in the class are ignored.
    12 What use of command line parameter cmd file?
    It is a command line argument that allows you to specify a file that contain a set of arguments for r20run.
    13 What is WHEN-Database-record trigger?
    Fires when oracle forms first marks a record as an insert or an update. The trigger fires as soon as oracle forms determines through validation that the record should be processed by the next post or commit as an insert or update. c generally occurs only when the operators modifies the first item in the record, and after the operator attempts to navigate out of the item.
    14 What is use of term?
    The term file which key is correspond to which oracle report functions.
    15 What is trigger associated with the timer?
    When-timer-expired.
    16 What is the use of transactional triggers?
    Using transactional triggers we can control or modify the default functionality of the oracle forms.
    17 What is the use of place holder column?
    A placeholder column is used to hold calculated values at a specified place rather than allowing is to appear in the actual row where it has to appear.
    18 What is the use of image_zoom built-in?
    To manipulate images in image items.
    19 What is the use of hidden column?
    A hidden column is used to when a column has to embed into boilerplate text.
    20 What is the use of break group?
    A break group is used to display one record for one group ones. While multiple related records in other group can be displayed.
    21 What is the remove on exit property?
    For a modelless window, it determines whether oracle forms hides the window automatically when the operators navigates to an item in the another window.
    22 What is the purpose of the product order option in the column property sheet?
    To specify the order of individual group evaluation in a cross products.
    23 What is the maximum no of chars the parameter can store?
    The maximum no of chars the parameter can store is only valid for char parameters, which can be upto 64K. No parameters default to 23Bytes and Date parameter default to 7Bytes.
    24 What is the main diff. bet. Reports 2.0 & Reports 2.5?
    Report 2.5 is object oriented.
    25 What is the frame & repeating frame?
    A frame is a holder for a group of fields. A repeating frame is used to display a set of records when the no. of records that are to displayed is not known before.
    26 What is the difference between OLE Server & Ole Container?
    An Ole server application creates ole Objects that are embedded or linked in ole Containers ex. Ole servers are ms_word & ms_excel. OLE containers provide a place to store, display and manipulate objects that are created by ole server applications. Ex. oracle forms is an example of an ole Container.
    27 What is the difference between object embedding & linking in Oracle forms?
    In Oracle forms, Embedded objects become part of the form module, and linked objects are references from a form module to a linked source file.
    28 What is the difference between boiler plat images and image items?
    Boiler plate Images are static images (Either vector or bit map) that you import from the file system or database to use a graphical elements in your form, such as company logos and maps. Image items are special types of interface controls that store and display either vector or bitmap images. Like other items that store values, image items can be either base table items(items that relate directly to database columns) or control items. The definition of an image item is stored as part of the form module FMB and FMX files, but no image file is actually associated with an image item until the item is populate at run time.
    29 What is the difference between $$DATE$$ & $$DBDATE$$ $$DBDATE$$ retrieves the current database date $$date$$ retrieves the current operating system date.
    30 What is the diff. when Flex mode is mode on and when it is off?
    When flex mode is on, reports automatically resizes the parent when the child is resized.
    31 What is the diff. when confine mode is on and when it is off?
    When confine mode is on, an object cannot be moved outside its parent in the layout.
    32 What is the diff. bet. setting up of parameters in reports 2.0 reports 2.5?
    LOVs can be attached to parameters in the reports 2.5 parameter form.
    33 What is the advantage of the library?
    Libraries provide a convenient means of storing client-side program units and sharing them among multiple applications. Once you create a library, you can attach it to any other form, menu, or library modules. When you can call library program units from triggers menu items commands and user named routine, you write in the modules to which you have attach the library. When a library attaches another library, program units in the first library can reference program units in the attached library. Library support dynamic loading-that is library program units are loaded into an application only when needed. This can significantly reduce the run-time memory requirements of applications.
    34 What is term?
    The term is terminal definition file that describes the terminal form which you are using r20run.
    35 What is system.coordination_operation?
    It represents the coordination causing event that occur on the master block in master-detail relation.
    36 What is synchronize?
    It is a terminal screen with the internal state of the form. It updates the screen display to reflect the information that oracle forms has in its internal representation of the screen.
    37 What is strip sources generate options?
    Removes the source code from the library file and generates a library files that contains only pcode. The resulting file can be used for final deployment, but can not be subsequently edited in the designer. ex. f45gen module=old_lib.pll userid=scott/tiger strip_source YES output_file
    38 What is relation between the window and canvas views?
    Canvas views are the back ground objects on which you place the interface items (Text items), check boxes, radio groups etc.,) and boilerplate objects (boxes, lines, images etc.,) that operators interact with us they run your form . Each canvas views displayed in a window.
    39 What is pop list?
    The pop list style list item appears initially as a single field (similar to a text item field). When the operator selects the list icon, a list of available choices appears.
    40 What is new_form built-in?
    When one form invokes another form by executing new_form oracle form exits the first form and releases its memory before loading the new form calling new form completely replace the first with the second. If there are changes pending in the first form, the operator will be prompted to save them before the new form is loaded.
    41 What is lexical reference? How can it be created?
    Lexical reference is place_holder for text that can be embedded in a sql statements. A lexical reference can be created using & before the column or parameter name.
    42 What is forms_DDL?
    Issues dynamic Sql statements at run time, including server side pl/SQl and DDL
    43 What is difference between open_form and call_form?
    when one form invokes another form by executing open_form the first form remains displayed, and operators can navigate between the forms as desired. when one form invokes another form by executing call_form, the called form is modal with respect to the calling form. That is, any windows that belong to the calling form are disabled, and operators cannot navigate to them until they first exit the called form.
    44 What is bind reference and how can it be created?
    Bind reference are used to replace the single value in sql, pl/sql statements a bind reference can be created using a (:) before a column or a parameter name.
    45 What is an user exit used for?
    A way in which to pass control (and possibly arguments ) form Oracle report to another Oracle products of 3 GL and then return control ( and ) back to Oracle reports.
    46 What is an OLE?
    Object Linking & Embedding provides you with the capability to integrate objects from many Ms-Windows applications into a single compound document creating integrated applications enables you to use the features form .
    47 What is an object group?
    An object group is a container for a group of objects; you define an object group when you want to package related objects, so that you copy or reference them in other modules.
    48 What is an anchoring object & what is its use?
    An anchoring object is a print condition object which used to explicitly or implicitly anchor other objects to itself.
    49 What is a User_exit?
    Calls the user exit named in the user_exit_string. Invokes a 3Gl program by name which has been properly linked into your current oracle forms executable.
    50 What is a timer?
    Timer is an "internal time clock" that you can programmatically create to perform an action each time the timer expires.
    51 What is a Text_io Package?
    It allows you to read and write information to a file in the file system.
    52 What is a text list?
    The text list style list item appears as a rectangular box which displays the fixed number of values. When the text list contains values that can not be displayed, a vertical scroll bar appears, allowing the operator to view and select undisplayed values.
    53 What is a property clause?
    A property clause is a named object that contains a list of properties and their settings. Once you create a property clause you can base other object on it. An object based on a property can inherit the setting of any property in the clause that makes sense for that object.
    54 What is a physical page ? & What is a logical page ?
    A physical page is a size of a page. That is output by the printer. The logical page is the size of one page of the actual report as seen in the Previewer.
    55 What is a library?
    A library is a collection of subprograms including user named procedures, functions and packages.
    56 What is a difference between pre-select and pre-query?
    Fires during the execute query and count query processing after oracle forms constructs the select statement to be issued, but before the statement is actually issued. The pre-query trigger fires just before oracle forms issues the select statement to the database after the operator as define the example records by entering the query criteria in enter query mode. Pre-query trigger fires before pre-select trigger.
    57 What is a combo box?
    A combo box style list item combines the features found in list and text item. Unlike the pop list or the text list style list items, the combo box style list item will both display fixed values and accept one operator entered value.
    58 What does the term panel refer to with regard to pages?
    A panel is the no. of physical pages needed to print one logical page.
    59 What are visual attributes?
    Visual attributes are the font, color, pattern proprieties that you set for form and menu objects that appear in your application interface.
    60 What are three panes that appear in the run time pl/sql interpreter?
    1.Source pane. 2. interpreter pane. 3. Navigator pane.
    Regards
    B RANGARAJAN

  • BO and SQL Programming question

    Post Author: Khorace
    CA Forum: Olap
    Hello,
             I am a new BO developer and I have a sql/ BO/ question. Why is it that my sql code can return the currect result set (from the database) but from the universe my data does not reflect the same? Any help is appreciated.

    Post Author: amr_foci
    CA Forum: Olap
    you should revise back the generated SQL code by the WebI, and check it, if its not the expected query then you've to check ur contexts in the universe desinger
    i think its a matter of contexts or restrictions or some missing joins
    good luck

  • Pl/sql vs sql basic question

    Hi,
    I have a very very basic question, so excuse me for that... I just would like to know the difference ( and the difference in usage) between sql and pl/sql?
    thank you
    Yann

    SQL - the structured query language - is the language available for extracting data from the database. It is a 4GL, and each command stands alone and performs a database action.
    PL/SQL is the 3GL primarily intended to control the flow of a series of SQL commands. PL/SQL does not, in any way, interact with the data in the database. It does, however, allow SQL statements to be called, or even created, in a specific order.
    SQL is capable of a LOT more than people usually realize. Unfortunate, as people often create PL/SQL programs when single SQL statements will do the job. I encourage reading the O'Reilly 'Mastering Oracle SQL' book ... only after fiunishing that book do I recommend any of Feuerstein's excellent PL/SQL books.

  • OPEN SQL performance question

    Hi friends,
    I'm going to read and process data in an interface coded in ABAP and OPEN SQL. To improve efficiency and reliability I'm processing the data in packets of a fixed size of rows - reading rows up to a predetermined numer into an internal table which then is processed and then finaly written back to database followed by "commit work". Then the process will continue with reading the next fixed number of rows, process them, and so on ...
    The general question is, which is the most efficient way to implement this scenario?
    I think of two basic approaches:
    1.1) Loop over results from a cursor using FETCH NEXT CURSOR inside a LOOP appending the lines to the internal table.
    2.1) Execute SELECT ... INTO TABLE <itab> FROM <table> UP TO <data packet size> ROWS.
    My assumtion is that approach 2 would be the more effecient, is that correct?
    The processed data will be written back to the database in one single statement:
    2.2) INSERT <table> FROM TABLE <itab>
    Which I assume is more efficient than doing the same using multiple inserts within a loop?
    Regards,
    Christian

    In native SQL you can also use the packet options.
    SELECT  <Fields name>      appending corresponding fields of table <Internal table>
                <b>package size 20000</b>
                FROM <Database table name>
                WHERE <Condition>.
    ENDSELECT.
    By using this the system will fetch the records from database table in packets [20000 records per package]
    Regards
    Aman

  • Interactive Reports - SQL Source Question

    Background
    Apex 3.1 is installed on Oracle 10g instance on local machine but all data is stored on a remote machine on Oracle 9 & 10 instances.
    This data is also used by another piece of software, which directly manipulates the data.
    The Apex Application that I am developing is to be used as a Quick Find/KPI Reporting tool and is setup to utilise DBLinks and Synonyms.
    Within the remote data, we have a mapping table that contains user specific alias' for field names, which the users set using the other piece of software. There can be up to 5 mappings per table field each defined as LNG01, LNG02,etc.
    In order to provide the same field Alias' in the Apex application, I have created a PL/SQL function to return the field alias and return a string value containing the final SQL.
    Problem
    In standard reports, this would work correctly as you could return a SQL statement in a string and it handled it with no problems.
    However, due to Interactive Reports not supporting this, I have tried to find code to pass in the string SQL Statement to return a TABLE or PIPELINED datasource.
    The string SQL statement will vary for each time it is used so the string SQL statement is effectively built as dynamic SQL
    This causes as problem as I will never be able to define the ROWTYPE for a type TABLE variable as the field names will not be constant.
    Can you tell me if there is any way to create a SQL source that could be used for the Interactive Report based on dynamic SQL?
    Alternatively, if you can provide any alternatives to finding a solution I would be most grateful.
    Apologies if this question has been posted before.
    Thanks in advance.
    Stuart

    Stuart,
    You could:
    1) Create page items, one for each dynamic column header (e.g. P1_OBJECT_NAME_HEADER, etc).
    2) Create a page process, to run when the page is loaded, that populates each item with the appropriate text. This can pull the column header text from your remote source.
    3) Use a static query as your interactive report source:
        select objname,
               objuniqueid,
               objtypecode,
               objsitearea,
               objdesc,
               objdesc2,
               objlocationid,
               objcommission
          from cdoweb_om4) Edit the interactive report attributes -- use APEX substitution string syntax to reference the item values (e.g. "&P1_OBJECT_NAME_HEADER." without the quotes) instead of static column headers.
    For more information on using substitution strings:
    http://download.oracle.com/docs/cd/E10513_01/doc/appdev.310/e10499/concept.htm#BEIFGFJF
    - Marco

  • SQL statement question

    I'm trying compare two table in Oracle and with a firstname and
    lastname
    matches fill-in a pager pin number.
    This is the sql statement I'm running
    update addressbook2 set pin =
    (select pin from phonebook where
    phonebook.firstname=addressbook2.firstname
    and
    phonebook.lastname=addressbook2.lastname)
    where addressbook2.firstname IN (select firstname from phonebook)
    and addressbook2.lastname IN (select lastname from phonebook)
    but I get an error message saying:
    ORA-01427: single-row subquery returns more than one row
    My question is can I update the table even when there are
    duplicates in the tables. The query runs perfect when both
    tables are unique.
    Thank you for any help.
    MN
    null

    I presume you are trying to update the pin of only those people
    in the addressbook table that also exist in the phonebook table.
    The following will work:
    update addressbook a
    set a.pin = (
    select f.pin from phonebook f
    where f.fname = a.fname
    and f.lname = a.lname
    ie remove the last two lines from your DML statement.. be aware
    that you are using a denormalised design (pin is not normalised
    on the primary key) and the use of first and last names as a
    method of identifying people is not a good idea (does 'smith' =
    'smyth'?)
    MN (guest) wrote:
    : I'm trying compare two table in Oracle and with a firstname and
    : lastname
    : matches fill-in a pager pin number.
    : This is the sql statement I'm running
    : update addressbook2 set pin =
    : (select pin from phonebook where
    : phonebook.firstname=addressbook2.firstname
    : and
    : phonebook.lastname=addressbook2.lastname)
    : where addressbook2.firstname IN (select firstname from
    phonebook)
    : and addressbook2.lastname IN (select lastname from phonebook)
    : but I get an error message saying:
    : ORA-01427: single-row subquery returns more than one row
    : My question is can I update the table even when there are
    : duplicates in the tables. The query runs perfect when both
    : tables are unique.
    : Thank you for any help.
    : MN
    null

  • SQL performance question

    My DB has a big table (STATUS_LOG) that contains operational log of 30 hardware devices – each record in this table stores the information about the status of a particular device in a particular point of time. Records are being added to the table all the time.
    At any point of time I want to know what the latest status of a particular device was. For this reason I plan to create a new table in the DB (to call it LAST_DEVICE_STATUS) that will have 30 records (one for each device). Each record of LAST_DEVICE_STATUS will contain a pointer to a record in STATUS_LOG table – the latest status records for this particular device; it will be updated each time a new record added to STATUS_LOG table. This way I will avoid querying STATUS_LOG table (which is really huge).
    My questions are:
    1. Does it seam to be a correct design?
    2. Is there a way in SQL to query huge tables efficiently in order to find the latest record that was added t the tables for a particular device? For your information, each record in STATUS_LOG contains a timestamp which can be used for finding the latest records.
    Thank you,
    Mark.

    I would stay away from analytic functions in this case since they are not “short-circuit friendly” …
    that is, whatever analytic function would get used, the entire data set would have to be processed
    before any meaningful filtering can take place.
    With the proper index in place … on device and timestamp … one could easily get the record with the
    max timestamp for each device with minimum IO.
    Here is a table with 1.2 million rows for 30 devices:
    create table dh
    ( dev        number      not null
    ,ts         date        not null
    ,status     varchar(1)  not null
    ,chr        char(100)   not null
    create index dh_idx on dh (dev,ts);
    flip@FLOP> select count(*) from dh;
      COUNT(*)
       1200000
    Elapsed: 00:00:00.64
    flip@FLOP> alter session set nls_date_format='yyyy-mon-dd hh24:mi:ss';
    Session altered.
    Elapsed: 00:00:00.00
    flip@FLOP>
    flip@FLOP> select dev, ts, status
      2  from ( select * from dh where dev = 5
      3         order by ts desc
      4       )
      5  where rownum < 2;
           DEV TS                   S
             5 2007-aug-13 14:03:32 A
    Elapsed: 00:00:00.00
    flip@FLOP>
    flip@FLOP> explain plan for
      2  select dev, ts, status
      3  from ( select * from dh where dev = 5
      4         order by ts desc
      5       )
      6  where rownum < 2;
    Explained.
    Elapsed: 00:00:00.04
    flip@FLOP>
    flip@FLOP> select * from table(dbms_xplan.display());
    PLAN_TABLE_OUTPUT
    Plan hash value: 1288316266
    | Id  | Operation                      | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT               |        |     1 |    24 |     3   (0)| 00:00:01 |
    |*  1 |  COUNT STOPKEY                 |        |       |       |            |          |
    |   2 |   VIEW                         |        | 35016 |   820K|     3   (0)| 00:00:01 |
    |   3 |    TABLE ACCESS BY INDEX ROWID | DH     | 35016 |  4308K|     3   (0)| 00:00:01 |
    |*  4 |     INDEX RANGE SCAN DESCENDING| DH_IDX |     1 |       |     2   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - filter(ROWNUM<2)
       4 - access("DEV"=5)
           filter("DEV"=5)
    Note
       - dynamic sampling used for this statement
    22 rows selected.
    Elapsed: 00:00:00.05
    Should you want a Dashboard of sorts, for just 30 devices, I would just amalgamate that query 30 times …
    here is for 3 of them …
    flip@FLOP> select t05.dev dev05, t05.ts ts05, t05.status status05
      2        ,t13.dev dev13, t13.ts ts13, t13.status status13
      3        ,t18.dev dev18, t18.ts ts18, t18.status status18
      4  from ( select *
      5         from ( select * from dh where dev = 5
      6                order by ts desc
      7              )
      8         where rownum < 2
      9       ) t05
    10      ,( select *
    11         from ( select * from dh where dev = 13
    12                order by ts desc
    13              )
    14         where rownum < 2
    15       ) t13
    16      ,( select *
    17         from ( select * from dh where dev = 18
    18                order by ts desc
    19              )
    20         where rownum < 2
    21       ) t18
    22  ;
         DEV05 TS05                 S      DEV13 TS13                 S      DEV18 TS18                 S
             5 2007-aug-13 14:03:32 A         13 2007-aug-13 14:03:32 A         18 2007-aug-13 14:03:32 A
    Elapsed: 00:00:00.01
    flip@FLOP> explain plan for
      2  select t05.dev dev05, t05.ts ts05, t05.status status05
      3        ,t13.dev dev13, t13.ts ts13, t13.status status13
      4        ,t18.dev dev18, t18.ts ts18, t18.status status18
      5  from ( select *
      6         from ( select * from dh where dev = 5
      7                order by ts desc
      8              )
      9         where rownum < 2
    10       ) t05
    11      ,( select *
    12         from ( select * from dh where dev = 13
    13                order by ts desc
    14              )
    15         where rownum < 2
    16       ) t13
    17      ,( select *
    18         from ( select * from dh where dev = 18
    19                order by ts desc
    20              )
    21         where rownum < 2
    22       ) t18
    23  ;
    Explained.
    Elapsed: 00:00:00.05
    flip@FLOP> select * from table(dbms_xplan.display());
    PLAN_TABLE_OUTPUT
    Plan hash value: 3204562936
    | Id  | Operation                          | Name   | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                   |        |     1 |    72 |   329   (1)| 00:00:05 |
    |   1 |  MERGE JOIN CARTESIAN              |        |     1 |    72 |   329   (1)| 00:00:05 |
    |   2 |   MERGE JOIN CARTESIAN             |        |     1 |    48 |   219   (1)| 00:00:04 |
    |   3 |    VIEW                            |        |     1 |    24 |   109   (0)| 00:00:02 |
    |*  4 |     COUNT STOPKEY                  |        |       |       |            |          |
    |   5 |      VIEW                          |        | 34706 |   813K|   109   (0)| 00:00:02 |
    |   6 |       TABLE ACCESS BY INDEX ROWID  | DH     | 34706 |  4270K|   109   (0)| 00:00:02 |
    |*  7 |        INDEX RANGE SCAN DESCENDING | DH_IDX | 34706 |       |    82   (0)| 00:00:02 |
    |   8 |    BUFFER SORT                     |        |     1 |    24 |   219   (1)| 00:00:04 |
    |   9 |     VIEW                           |        |     1 |    24 |   109   (0)| 00:00:02 |
    |* 10 |      COUNT STOPKEY                 |        |       |       |            |          |
    |  11 |       VIEW                         |        | 34861 |   817K|   109   (0)| 00:00:02 |
    |  12 |        TABLE ACCESS BY INDEX ROWID | DH     | 34861 |  4289K|   109   (0)| 00:00:02 |
    |* 13 |         INDEX RANGE SCAN DESCENDING| DH_IDX | 34861 |       |    82   (0)| 00:00:02 |
    |  14 |   BUFFER SORT                      |        |     1 |    24 |   220   (1)| 00:00:04 |
    |  15 |    VIEW                            |        |     1 |    24 |   110   (0)| 00:00:02 |
    |* 16 |     COUNT STOPKEY                  |        |       |       |            |          |
    |  17 |      VIEW                          |        | 35016 |   820K|   110   (0)| 00:00:02 |
    |  18 |       TABLE ACCESS BY INDEX ROWID  | DH     | 35016 |  4308K|   110   (0)| 00:00:02 |
    |* 19 |        INDEX RANGE SCAN DESCENDING | DH_IDX | 35016 |       |    83   (0)| 00:00:02 |
    Predicate Information (identified by operation id):
       4 - filter(ROWNUM<2)
       7 - access("DEV"=13)
           filter("DEV"=13)
      10 - filter(ROWNUM<2)
      13 - access("DEV"=18)
           filter("DEV"=18)
      16 - filter(ROWNUM<2)
      19 - access("DEV"=5)
           filter("DEV"=5)
    Note
       - dynamic sampling used for this statement
    43 rows selected.
    Elapsed: 00:00:00.04

  • SQL PLUS QUESTIONS

    According to the tables and attributes below I need to solve 25 questions. I answered some of them and some of them I couldn't solve. I need your help please.
    school (sch_code, sch_name, sch_phone, sch_dean)
    advisor (adv_code, adv_fname, adv_lname, adv_phone, sch_code)
    major (maj_code, maj_desc, sch_code)
    maj_adv (maj_code, adv_code)
    student (std_code     , std_lname, std_fname, std_gend, maj_code, std_dob)
    grade (std_code,     gr_lname, gr_fname, gr_t1, gr_t2, gr_hw, gr_pr)
    create table school
    (sch_code varchar2(8) constraint school_sch_code_pk primary key,
    sch_name varchar2(50),
    sch_phone varchar2(12),
    sch_dean varchar2(20));
    insert into school values (‘BUS’, ‘School of Business’, ‘281-283-3100’, ‘Ted Cummings’);
    insert into school values (‘EDU’, ‘School of Education’, ‘281-283-3600’,’Dennis Spuck’);
    insert into school values (‘HSH’, ‘School of Humanities and Human Sciences’, ‘281-283-3333’, ‘Bruce Palmer’);
    insert into school values (‘SCE’, ‘School of Science and Computer Engineering’, ‘281-283-3700’,’Sadegh Davari’);
    create table advisor
    (adv_code     varchar2(08)     constraint advisor_adv_code_pk primary key,
    adv_lname     varchar2(15),
    adv_fname     varchar2(15),
    adv_phone     varchar2(12),
    sch_code     varchar2(8) constraint advisor_sch_code_fk references school (sch_code));
    insert into advisor values (‘A1’, ‘Porter’, ‘Mattie’, ‘281-283-3163’, ‘BUS’);
    insert into advisor values ( ‘A2’, ‘Grady’, ‘Perdue’ ,‘281-283-3400’, ‘BUS’);
    insert into advisor values (‘A3’, ’Tran’, ’Van’, ‘281-283-3203’, ‘BUS’);
    insert into advisor values (‘A4’, ‘Saleem’, ‘Naveed’, ‘281-283-3202’, ‘BUS’);
    insert into advisor values (‘A5’, ‘Kwok-Bon’, ‘Yue’, ‘281-283-3864’, ‘SCE’);
    insert into advisor values (‘A6’, ‘Jones’, ‘Lisa’, ‘281-283-3551’, ‘EDU’);
    insert into advisor values (‘A7’, ‘Palmer’, ‘Bruce’, ‘281-283-3445’, ‘HSH’);
    create table major
    (maj_code     varchar2(10)     constraint major_maj_code_pk primary key,
    maj_desc      varchar2(30),
    sch_code     varchar2(8)      constraint major_sch_code_fk references school(sch_code));
    insert into major values (‘ACCT’, ‘Accounting’, ‘BUS’);
    insert into major values (‘FINC’, ‘Finance’, ‘BUS’);
    insert into major values (‘ISAM’, ‘Management Information Systems’, ‘BUS’);
    insert into major values (‘CSCI’, ‘Computer Science’, ‘SCE’);
    insert into major values (‘HIST’, ‘History’, ‘HSH’);
    insert into major values (‘INST’, ‘Instructional Technology’, ‘EDU’);
    create table maj_adv
    (maj_code      varchar2(10)     constraint maj_adv_maj_code_fk references major (maj_code),
    adv_code     varchar2(08)     constraint maj_adv_adv_code_fk references advisor (adv_code),
    constraint maj_adv_maj_code_adv_code_cpk primary key (maj_code, adv_code));
    insert into maj_adv values (‘ACCT’, ’A1’);     
    insert into maj_adv values (‘ACCT’, ‘A2’);
    insert into maj_adv values (‘FINC’, ’A2’);
    insert into maj_adv values (‘ISAM’, ’A3’);
    insert into maj_adv values (‘ISAM’, ’A4’);
    insert into maj_adv values (‘CSCI’, ‘A5’);
    insert into maj_adv values (‘INST’, ‘A6’);
    insert into maj_adv values (‘HIST’, ‘A7’);
    create table student
    (std_code     varchar2(9),
    std_lname     varchar2(15)     constraint student_std_lname_nn not null,
    std_fname     varchar2(15)     constraint student_std_fname_nn not null,
    std_gend     varchar2(8),     
    maj_code     varchar2(10)     constraint student_maj_code1_fk references major (maj_code),
    std_dob     date,
    constraint student_std_code_pk primary key (std_code));
    insert into student values (‘S1’, ‘Jordan’, ‘Michael’, ‘F’, ‘FINC’, to_date(‘10-Mar-1962’, 'DD-Mon-YYYY'));
    insert into student values (‘S2’, ‘Barkley’, ‘Charles’, ‘M’, null, to_date(‘12-Sep-1964’, 'DD-Mon-YYYY'));
    insert into student values (‘S3’, ‘Johnson’, ’Magic’, ‘M’, ‘ACCT’, to_date(‘13-Sep-1960’, 'DD-Mon-YYYY'));
    insert into student values (‘S4’, ‘Williams’, ‘Serena’, ‘F’,‘ISAM’, to_date(‘23-Oct-1980’, 'DD-Mon-YYYY'));
    insert into student values (‘S5’, ‘Duncan’, ‘Tim’, ‘M’, ‘ISAM’, to_date(‘07-Aug-1972’, 'DD-Mon-YYYY'));
    insert into student values (‘S6’, ‘Graff’, ’Steffi’, ‘F’, ‘CSCI’, to_date(‘30-Apr-1962’, 'DD-Mon-YYYY'));
    insert into student values (‘S7’, ‘Navratilova’, ’Martina’, ‘F’, ’ACCT’, to_date(‘18-Dec-1972’, 'DD-Mon-YYYY'));
    REMARK insert into student (std_code, std_lname, std_fname, std_dob)
    REMARK values (‘S2’, ‘Barkley’, ‘Charles’, to_date(‘12-Sep-1964’,'DD-Mon-YYYY'));
    create table grade
    (std_code     varchar2(9)     constraint grade_std_code_pk primary key
                        constraint grade_std_code_fk references student (std_code),
    gr_lname     varchar2(15)     constraint grade_gr_lname_nn not null,
    gr_fname     varchar2(15)     constraint grade_gr_fname_nn not null,
    gr_t1          number(5),     constraint grade_gr_t1_cc check (gr_t1 between 0 and 100),
    gr_t2          number(5),     
    gr_hw          number(5),     
    gr_pr          number(5));
    insert into grade values (‘S1’, ‘Jordan’, ‘Michael’, 90, 80, 98, 90);
    insert into grade values (‘S2’, ‘Barkley’, ‘Charles’, 60, 100, 100, 60);
    insert into grade values (‘S3’, ‘Johnson’, ’Magic’, 88, 98, 96, 98);
    insert into grade values (‘S4’, ‘Williams’, ‘Serena’, 92, 92, 92, 92);
    insert into grade values (‘S5’, ‘Duncan’, ‘Tim’, 94, 90, 94, 96);
    insert into grade values (‘S6’, ‘Graff’, ’Steffi’, 80, 84, 83, 72);
    insert into grade values (‘S7’, ‘Navratilova’, ’Martina’, 91, 88, 94, 95);
    the questions are:
    Give the commands for the following:
    1.     Display the names of students who don't have a major.
    2.     Display the names of students whose last name has two "o" in it.
    3.     Display the names of students whose first name includes an "e" in it.
    4.     Display the names of students whose first name has exactly five characters in it.
    5.     Display the names of students whose test 1 grade is higher than test 2 grade.
    6.     Display the names of students whose project grade is between tests 1 and test 2 grades.
    7.     Give the name of student whose last name starts with the character "B" or who never turned in homework.
    8.     Give the command that will list two columns and one record. The first column will have the heading "Major" and "ACCT" as the value. The second column will have the heading “MIS_Count” and will display the number of accounting advisors.
    9.     Display the name of the student whose test 1 score is higher than the average on test 1.
    10.     Give the first and last names of students who scored above average on test 1 as well as above average on test 2.
    11.     Display the system date variable using the dual table.
    12.     Display the system date variable using the grade table making sure that the date is displayed only once.
    13.     Give the name of the student who is the oldest student and scored the highest on the first test.
    14.     List different majors and number of advisors for these majors.
    15.     Display the names of students who don't have grade for any item.
    16.     Display the names of the students who don't have grade for at least one item.
    17.     Display names of students who have the same major as “Michael Jordan.”
    18.     Give the names of students whose average on test 1 and test 2 is greater than the average on homework and project.
    19.     Display the name and average on test 1 and test 2 for each student.
    20.     Display the number of students in student table using three different methods.
    21.     Display the number accounting students in the student table.
    22.     Display the number of accounting and finance students in the student table.
    23.     Display the average on test 1 and test 2 for female students.
    24.     Display the number of accounting and finance students whose test 1 grades are higher than the average on test 1.
    25.     Display the name of the major that has more than two students.
    I am stuck with the following questions(1,12,13, 15,16,17,24) and the rest I finished them but I am not quite sure.
    Thank you and looking forward to hear your suggestions.

    Hi,
    user11956564 wrote:
    13.     Give the name of the student who is the oldest student and scored the highest on the first test.
    I can get the oldest student and the highest score but in two different queries. My question is how can I use them together in one query
    List oldest student in class
    select std_fname, std_lname from student
    where std_dob = (select min(std_dob) from student);
    List highest grade in class
    select gr_fname, gr_lname from grade
    where gr_t1 = (select max(gr_t1) from grade);
    because they are two tables. I think this is a confusing question: I'm not sure what the expected output is, or what the lesson you're supposed to learn is.
    One way of combining results from different tables is UNION. As long as two queries produce the same number of columns, and the same datatypes, they can be combined with UNION.
    For example: the following query displays the name of the employee whose job is 'PRESIDENT' (from the scott.emp table) and the name of department 10 (from the scott.dept table) in one query:
    SELECT  ename
    ,       job
    FROM  scott.emp
    WHERE   job = 'PRESIDENT'
        UNION
    SELECT  dname
    ,       TO_CHAR (deptno)
    FROM    scott.dept
    WHERE   deptno = 10
    ;Both SELECT clauses have 2 columns.
    This 1st column in the 1st part is a VARCHAR2, so the 1st column of the 2nd part must also be a VARCHAR2. It is.
    The 2nd column in the 1st part is a VARCHAR2, so the 2nd column of the 2nd part must also be a VARCHAR2. However, deptno (which we want to display here) is not a VARCHAR2, but a NUMBER; that's why I used TO_CHAR to put a VARCHAR2 value in that place.
    17.     Display names of students who have the same major as “Michael Jordan.”
    here is what I did
    select std_fname, std_lname, maj_code
    from student
    where maj_code=(select maj_code
    from studentJordan');
    I am not sure if my answer is correct or not because in the output I got Michael JordanThis question is unclear, too.
    Assuming you do not want Michael Jordan in the results, add a 2nd condition to the WHERE clause, so that you select
    people who have the right major (which you say you are doing correctly, but the query seems to have lost something when you posted it)
    AND
    people who are not named Micheal Jordan
    24.     Display the number of accounting and finance students whose test 1 grades are higher than the average on test 1.
    It was too confusing for me.Are you sure?
    Look at what you tried for 13.
    select  std_fname, std_lname from student
    where   std_dob = (select min(std_dob) from student);
    select  gr_fname, gr_lname from grade
    where   gr_t1 = (select max(gr_t1) from grade);The function for average (AVG) is used very much like the other aggregate function, like MIN and MAX.

  • Sql developer: question about exporting data

    Hi,
    we're recently working with sql-developer. i've got a question about how we can export query results to txt/csv files for use in other applications.
    First a problem: if we start a query that looks like this:
    select * from
    select * from A where start_date = &date
    ) a,
    select * from B where start_date = &date
    ) b
    where a.name = b.name
    Sql-developer asks twice to input a value for the variable 'date', although it's the same variable and it's supposed to have the same value.
    We solve this by making a script:
    first we define the variable, then we put the query.
    When we start the script, the query runs ok and sql developer asks to input the value for the variable once.
    But now the result of the query is shown in the script output. The script output seems to be limited in number of lines and difficult to export.
    So my question is: what's the best way to export query results to txt/csv files, avoiding the problem mentioned above?
    i hope there is a solution where we can use a single query or script.
    Thanks in advance!

    Using bind variables like ":date" should solve the problem of being asked twice for the same thing.
    Executing the query normally (F9), gives you the export options you require through the context menu inside the Results grid.
    Regards,
    K.

  • SQL Query Question

    Hi,
    I am trying to filter my output from the query based on some conditions but not able to figure out how. May be I am just overlooking at the issue or is it something tricky.
    So, I have a query returning 4 rows of output out of which I need to filter the rows. I have created a table from the result of the query that I need to filter to make it simple. So below is my create table script and values that are obtained from my original query.
    CREATE TABLE TEMPACCT
      SOURCEKEY           NUMBER,
      FLAG                VARCHAR2(1),
      ITEMID              NUMBER(9)                 ,
      ITEMNAME            VARCHAR2(10)               ,
      ITEMKEY             NUMBER(9)                
    Insert into tempacct values (0, 'N', 100, 'ITEM1' , 9647);
    Insert into tempacct values (0, 'N', 200, 'ITEM2' , 9648);
    Insert into tempacct values (9648, 'N', 100, 'ITEM3' , 9813);
    Insert into tempacct values (9647, 'Y', 100, 'ITEM4' , 9812);
    SQL> select * from tempacct;
    SOURCEKEY F     ITEMID ITEMNAME      ITEMKEY
             0 N        100 ITEM1            9647
             0 N        200 ITEM2            9648
          9648 N        100 ITEM3            9813
          9647 Y        100 ITEM4            9812
    SQL> Tempacct table is the table created from the resultset of my original query.
    So from the above output, what I need is 3 rows. The logic to filter out the row is - If any of the row thathas sourcekey that is same as Itemkey in any of the 4 rows and flag is Y then remove the row which have flag =N and only display the one with Falg = Y.
    Ok, so, in this case the desired output would be
    SOURCEKEY F     ITEMID ITEMNAME      ITEMKEY
             0 N        200 ITEM2            9648
          9648 N        100 ITEM3            9813
          9647 Y        100 ITEM4            9812So here we compared between the first row and the fourth row, and since the sourcekey in fourth row is same as itemkey in first row and Flag is 'Y' for fourth row, we keep 4th row and remove the first row since the flag is 'N'. (and sourcekey is 0. the row that gets removed will always have sourcekey =0) .
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Release 10.2.0.4.0 - 64bit Production
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for Linux: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - ProductionAppreciate your help.

    Hi,
    ARIZ wrote:
    Although the original question is already been answered, I had another small modification to the same question and also seeking some clarification. I do not want to open a new thread just for a similar question.I think you'll get better replies faster if you do start a new thread.
    Not counting this one, there have been 13 replies to this thread. Not many people who havn't already been participating in this thread are going to start reading a thread with 13 replies. Those who do are going to waste a lot of time reading about issues that have already been resolved, and the are likely to understand the remaining issues incorrectly.
    I have been following the thread from the beginnning, and I'm starting to get confused about what the unresolved issues are.
    I believe there are two things you still need:
    (1) An explanation of the solution I posted yesterday, involving the analytic COUNT function.
    (2) A solution for a new problem involving the same tables
    If I got that wrong, start a new thread, asking just what you need to know. Copy any relevant parts (like the CREATE TABLE and INSERT statements) from this thread. You can include a link to this thread, but do your best to make sure people don't have to use it.
    I realize that's more work for you, but getting the best results, and getting them quickly, sometimes does require more work.
    <h2>(1) An explanation of the solution I posted yesterday, involving the analytic COUNT function.</h2>
    ARIZ wrote:
    Hi Frank,
    Just out of curiosity, I was trying to understand the Count analytical function that you have used in the solution.
                    COUNT ( CASE
                                 WHEN  ac.flag = 'Y'
                           THEN  1
                             END
                        ) OVER ( PARTITION BY  CASE
                                                   WHEN  sourcekey = 0
                                       THEN  acctkey
                                       ELSE  sourcekey
                                               END
                                  )     AS y_cntSo what I am thinking is, this would first partition the row with acctkey ( where sourcekey =0) and sourcekey and then within that partition, it will check whether ac.flag = Y or not, if it is 'Y' then it would return count as 1 else 0. Am I correct? In the mean time I am also reading the tutorials on Count() analytical query. I'm not sure I understand your explanation.
    This is not partitioning first by x, and then by y. There is only one expression in the PARTITION BY clause. Most often, a PARTITION BY clause refers to some column in the table, for example:
    SELECT  ename
    ,       job
    ,       sal
    ,       AVG (sal) OVER (PARTITION BY job)  AS avg_sal_for_job
    FROM    scott.emp;This divides the result set into mutually exclusive parts; there will be as many such parts as there are distinct values for the PARTITION BY column. In the simple query above, if there happen to be 5 different values for job, you will get 5 independent averages.
    In your problem, there is no one column that defines a partition. That is, these two rows belong to the same partition:
    . SOURCEKEY F   ACCTKEY
             0 N       9647
          9647 Y       9812even though none of the 3 columns are the same. We could create a view that had a single column, telling to which partition each row belonged, like this:
    . SOURCEKEY F   ACCTKEY PART_NUM
             0 N       9648     9648
             0 N       9647         9647
          9648 N       9813         9648
          9647 Y       9812         9647where part_num is the result of a CASE expression:
    CASE
        WHEN  sourcekey = 0
        THEN  acctkey
        ELSE  sourcekey
    ENDWe could then use that new column, part_num, in a (very simple) PARTITION BY clause. But there is no need to create a view, even an in-line view, for that: we can (and I did) use the CASE expression directly in a (not so simple) PARTITION BY clause.
    Why did I use COUNT? The important thing about each partition is whether or not it includes any rows with flag='Y'. I don;t know of any function that directly answers that question. There are lots of ways to get the correct answer, but I think the one that corresponds most closely to the question we really want to ask:
    "Do any rows have flag='Y'?" is
    "How many rows have flag='Y'?"
    The analytic function COUNT (x) returns a number (possibly 0) of rows in the partition where x is not NULL. So, as the argument to COUNT, I used
    CASE
        WHEN  ac.flag = 'Y'
        THEN  1
    --  ELSE  NULL          -- I did not explicitly say this, but it is the default
    ENDwhich returns either
    (a) the literal number 1 or
    (b) NULL
    Instead of the literanl number 1, I could have used any literal or expression, of any data type, that is not NULL). all that matters is we produce something non-NULL for COUNT to count.
    <h2>(2) A solution for a new problem involving the same tables</h2>
    Also, I was trying to modify this query to fit my other similar requirement where I would need following output
    Original output:
    SOURCEKEY F    ACCTKEY
    0 N       9648
    0   N      9647
    9648 N       9813
    9647 Y       9812
    So, the query should be smart enough to return only the last two rows where sourcekey >0 which is
    SOURCEKEY F    ACCTKEY
    9648 N       9813
    9647 Y       9812
    And In case there are only first two 2 rows in the table then , it should return only those two row and not check for sourcekey > 0 which would be .
    SOURCEKEY F    ACCTKEY
    0 N       9648
    0   N      9647 Is it something that I should be using analytical function to solve this requirement. I am trying to accomplish this new requirement.If I understand this problem correctly, it does indeed involve mutually exclusive divisions, but in this problem, the divisions correspond more closely to a single column in the table. We want to divide the table into two mutually exclusive groups:
    (A) rows where soucekey > 0, and
    (B) rows where sourcekey = 0
    We could do that with a CASE expression, but there happens to be a built-in function that works very nicely.
    SIGN (sourcekey) returns
    (A) 1 if sourcekey > 0, and
    (B) 0 if sourcekey = 0
    But what do we want to do with those divisions? We want to display rows only from the "best" of those divisions, where division (A) is coinsidered "better" than division (B). That is, if there are any rows in division (A), then we want to display only rows in division (A), but if there are no rows in division (A), then (and only then) we want to display rows in divison (B).
    This is an example of a Top-N Query , where we want to display N items from the top of an ordered list. A typical top-N query uses an analytic function (either ROW_NUMBER, RANK or DENSE_RANK, depending on how we want to handle ties) to assign numbers to each row (lower numbers for the "better" rows), and then uses "WHERE f <= n" to display only the n "best" ones. (A special case, though a very common one, is where N=1, that is, we're only interested in the row (or rows, if there happens to be a tie) with the "best" value. In this case, most people find it cleare to say "WHERE f = 1" ratehr than "WHERE f <= 1". Your problem is an exmple ot that special case.)
    SELECT  sourcekey
    ,     flag
    ,     acctkey
    FROM     (
             SELECT  ac.sourcekey
             ,         NVL (ac.flag, 'N')     AS flag
             ,         ac.acctkey
             ,         DENSE_RANK () OVER (ORDER BY  SIGN (sourcekey)     DESC)     AS division_num
                FROM    itemtable     i
             ,         finance     f
             ,         acct     ac
               WHERE   i.itemtableid1      = f.parentid1
               AND         i.itemtableid2      = f.parentid2
             AND         f.financekey      = ac.financekey
               AND         i.parenttableid      = 19063
    WHERE     division_num     = 1
    ;Notice I talked about "mutually exclusiive *divisions* " above, not "mutually exclusive *partitions* ".
    There is no PARTITION BY in the analytic clause above. PARTITION BY means we want a separate, independent caluclation for each partition. Here, we want one single numbering for the entire result set.
    We want all rows that tie for the "best" to be numbered 1, so we have to use DENSE_RANK (or RANK) rather than ROW_NUMBER.

  • SQL Developer question

    Hi Folks
    I am using SQL Developer tool. I have a procedure with compilation errors so i can see that procedure with red X mark in SQL Developer tool.
    When am clicking on the procedure it is going to the editor there i can see "code"."grants","dependencies","references","details","profiles" tabs
    But i can't able to see "Errors" tab in the editor. And main thing is i didnt see any red lines in the editor for the invalid procedure
    And when i recompiled that procedure it got recompiled successfully and that red x mark is vanished.
    Here my question is the "Errors" tab is only appears when the procedure/function/package has errors and surprisingly i didnt see any red lines in the editor for invalid procedure (may be my proc has no errors).
    ps: i have asked this question in sql developer forum but i posted here as you may work on this
    Thanks

    Dear Sir
    I have this procedure Find_Emp
    create or replace
    procedure find_emp(p_in_empno in number)
    as
    v_ename emp.ename%type;
    begin
    select ename into v_ename from emp where empno=p_in_empno;
    dbms_output.put_line(v_ename);
    end;and i have done
    alter table emp add dname varchar2(10)I dont know why Find_Emp is invalid now,Folks can you please help.
    But that change doesnt affecting the below procs also, i mean these procs are not showing as invalid
    create or replace
    procedure test
    is
    cursor c is select ename,empno from emp;
    v_result c%rowtype;
    begin
    open c;
    loop
    fetch c into v_result;
    exit when c%notfound;
    dbms_output.put_line(v_result.ename||' '||v_result.empno);
    end loop;
    close c;
    end;
    and
    create or replace
    procedure p1
    AUTHID CURRENT_USER
    as
    v_cyc_dt varchar2(10);
    begin
    v_cyc_dt := '20120101';
    execute immediate 'create table t1 as
    select * from emp
    where hiredate >=to_date(''||v_cyc_dt||'',''yyyymmdd'')
    and rownum <= 1000';
    end p1;

  • PL/SQL performance questions

    Hi,
    I am responsible for a large, computation-intensive PL/SQL program that performs some batch processing on a large number of records.
    I am trying to improve the performance of this program and have a couple of questions that I am hoping this forum can answer.
    I am running Oracle 11.1.0.7 on Windows.
    1. How does compiling with DEBUG information affect performance?
    I found that my program units (packages, procedures, object types, etc) run significantly slower if they are compiled with debug information
    I am trying to understand why this is so. Does debug information instrument the code and result in more code that needs to be executed?
    Does adding debug information prevent compiler optimizations? both?
    The reason I ask this question is to understand if it is valid to compare the performance of two different implementations if they are both compiled with debug information. For example, if one approach is 20% faster when compiled with debug information, is it safe to assume that it will also be 20% faster in production (without debug information)? Or, as I expect, does the presence of debug information change the performance profile of the code?
    2. What is the best way to measure how long a PL/SQL program takes?
    I want to compare to approaches, such as using a VARRAY vs. a TABLE variable. I have been doing this by creating two test procedures that performs the same task using the two approaches I want to evalulate.
    How should I measure the time an approach takes so that it is not affected by other activity on my system? I have tried using CPU time (dbms_utility.get_cpu_time) and elapsed time. CPU time seems to be much
    more consistent between runs, however, I am concerned that CPU time might not reflect all the time the process takes.
    (I am aware of the profiler and have used that as well, however, I am at the point where profiling is providing diminishing returns).
    3. I tried recompiling my entire system to be native compiled but to my great surprise, did not notice any measurable difference in performance!
    I compiled all specification and bodies in all schemas to be native compiled. Can anyone explain why native compilation would not result in a significant performance improvement on a process that seems to be CPU-bound when it is running? Are there any other settings or additional steps that need to be performed for native compilation to be effective?
    Thank you,
    Eric

    Yes, debug must add instrumentation. I think that is the point of it. Whether it lowers the compiler optimisation level I don't know (I haven't read anywhere that it does) but surely if you stepping through code manually to debug it then you don't care.
    I don't know of a way to measure pure CPU time independently of other system activity. One common approach is to write a test program that repeats your sample code a large enough number of times for a pattern to emerge. To find how much time individual components contribute, dbms_profiler can be quite helpful (most conveniently via a button press in IDEs such as PL/SQL Developer, but it can also be invoked from the command line.)
    It is strange that no native compilation appears to make no difference. Are you sure everything is actually using it? e.g. is it shown as natively compiled in ALL_PLSQL_OBJECT_SETTINGS?
    I would not expect a PL/SQL VARRAY variable to perform any differently to a nested table one - I expect they have an identical internal implementation. The difference is that VARRAYs have much reduced functionality and a normally unhelpful limit setting.
    Edited by: William Robertson on Nov 6, 2008 11:49 PM

  • PL/SQL procedure questions

    I have a sample few questions in PL/SQL procedure. Any example will be great but even some words of wisdom will be hugely appreciated.
    1. Procedure A updating table t1. How can I reference the t1 (while updated by A) from another procedure?
    2. How to reference a cursor in procedure A from procedure B?
    3. How do I pass a cursor as a parameter in a cursor?
    4. Procedure A calls table B. A also updates table t1 and t2, while B updates table t3. Now if some error occurs in procedure B, what happens to the rows table t1, t2, t3 which were already updated? Do they rollback or commit?
    Thanks

    user13667036 wrote:
    I have a sample few questions in PL/SQL procedure. Any example will be great but even some words of wisdom will be hugely appreciated.
    1. Procedure A updating table t1. How can I reference the t1 (while updated by A) from another procedure?
    2. How to reference a cursor in procedure A from procedure B?
    3. How do I pass a cursor as a parameter in a cursor?
    4. Procedure A calls table B. A also updates table t1 and t2, while B updates table t3. Now if some error occurs in procedure B, what happens to the rows table t1, t2, t3 which were already updated? Do they rollback or commit?
    1. You reference table t1 the way you reference any other table. The fact that Proc A is updating the table has NOTHING to do with it.
    2. You can't. A proc has NO access to the internals of another proc. Proc B can CALL proc A and proc A can return a cursor as an OUT parameter that Proc B can reference.
    3. The same way you pas any other parameter. Why do you think it would be any different?
    4. They don't 'rollback' or 'commit' unless your code executes one of those statements or unless your code returns to a client that then issues an implicit or explicit commit/rollback.

Maybe you are looking for

  • Transaction similar to  S_ALR_87012177 (Customer Payment History screen)

    Hello Gurus Do you know some other standard transaction similar to S_ALR_87012177 (Customer Payment History screen) ? Thanks in advance

  • Payment method field ZLSCH is hidden on FI doc item.When can it be visible?

    Hello, where can i customize which FI item is relevant for entering payment method value in tcode FB01, FB02, FB03. I supposed that every customer or vendor item should display (and insert during FI document posting) payment method field. If i double

  • Javax.mail does not exist

    I would like to thank warnerja for your advise about the classpath. Thanks for the classpath information regarding the .jar files. Now when I start tomcat cat it runs appropriately. However I am still having a problem when i try to compile the messag

  • Input level resets every time using FaceTime

    Hi. I recently added a webcam to my Mac Mini to use with FaceTime.  (It's an IceCam 2).  Works fine for my needs, except every time I connect with Facetime, the input level gets reset to 0.  I'm able to change it back via system preferences, but is t

  • How long can I wait to purchase apple care

    I just but the iphone 4s world phone without apple care, but I will be back in the states in april. Can i purchase the apple care by then or will ti be too late?