Select query inside PL/SQL block.

Hello Experts,
I am just a beginner with PL/SQL.
If I write a select query from client like SQL dev and fire it against a database, it gives me result.
Eg: select * from employee;
Now when I use the same Query inside a PL/SQL block suppose:
Declare
begin
select * from employee;
end;
This gives error on execution, mentioning that an INTO is expected etc...
I have doubts here:
1. Can't I use a plain select inside a PL/SQL block (if so why?)
I know this is kind of very basic question, I tried searching this on the forum but could not find the thread, please redirect me to the link if this is already answered.

user8578271 wrote:
Hello Experts,
I am just a beginner with PL/SQL.
If I write a select query from client like SQL dev and fire it against a database, it gives me result.
Eg: select * from employee;
Now when I use the same Query inside a PL/SQL block suppose:
Declare
begin
select * from employee;
end;
This gives error on execution, mentioning that an INTO is expected etc...
I have doubts here:
1. Can't I use a plain select inside a PL/SQL block (if so why?) Because when you run a query in a tool like SQL Developer, or SQL*Plus or TOAD etc. then it opens up a cursor and fetches the data into internal memory structures before displaying it, and that is all done automatically and hidden from you. In PL/SQL, there is no interface to display the results of SQL queries, so you have to specifically tell it what to put the data into.
The syntax is (in basic terms)...
SELECT column1, column2... columnX
INTO variables or record structure
FROM ...Though that can only select a single row of data. If your query returns more than 1 row it will give a TOO_MANY_ROWS exception. If your query returns no rows you will get a NO_DATA_FOUND exception.
If you need to select multiple rows into variables etc., then you would need to "BULK COLLECT" into a collection/array structure, though this takes up valuable memory on the server and shouldn't be used unless necessary (and you understand the implications of doing it).

Similar Messages

  • Select statements inside a SQL Expression field

    Hello
    Why cannot we use the Select statements inside a SQL expression field in Crystal Reports ?
    Any alternatives for this...
    SELECT Top(1) "SomePrivateDatabase"."SPDname" FROM "SomePrivateDatabase"
    inner join "Subscriber" on
    "Subscriber"."SPDID" = "SomePrivateDatabase"."SPDID"
    inner join "UserDetails" on
    "UserDetails"."SPDID" = "SubscriberCore"."SPDID"
    Regards
    Srivatsa
    Edited by: Srivatsa Haridas on Dec 3, 2008 12:17 PM

    Hi Srivatsa,
    SQL Expressions is something the Database supports. We query the Client engine for a list of functions they make available. If the SQL Statement is not list it's not an option and therefore it won't work.
    Your work arounds are to use either a Stored Procedure, this is the most efficient way, all processing is done server side and CR simply waits for the data to format in the report. Another option is to use a
    Command Object, use one CO per report so try to get all data within the SQL statement. We simply pass the SQL to the server and wait for the result set, if you get an error it will be the SQL you typed in. Test in a SQL test tool first to confirm you are getting the data correctly.
    For more assistance in designing reports please post your report deisgn questions to the Reprot Design forums. I am moving this one to that queue.
    Thank you
    Don

  • No Data Found: Exception in SQL inside PL/SQL block

    Hi Friends
    I am trying to execute an SQL SELECT stmt inside a PL/SQL block. But when i execute the procedure, it gives me No Data Found Exception.
    I know it is because no row is fetched in the query, but the condition of the SELECT query i have specified is being satisfied, i have checked it by running it on the SQL prompt.
    But somehow, it is not running from inside the PL/SQL procedure.Can anybody help me out on this as to why is this happening?? I am giving my code for reference and have Highlighted the Query inside it:
    CREATE OR REPLACE procedure insert_sfdc_account
    as
    --DECLARE
    CURSOR C1 IS
    SELECT customer_code, name1, name2, name3, name4, phone_number, fax, web_address, industry_sector, customer_profile, customer_type,
    address, city, postal_code, country_key, zzcust_type, vat_code
    FROM load_cust_general
    WHERE account_group = 'ZSIT';
    v_cust_cur c1%ROWTYPE;
    -- type sales_tab is table of load_cust_sales_area%rowtype;
    v_sales_area load_cust_sales_area%ROWTYPE;
    -- v_sales_area sales_tab;
         v_salesorg varchar2(10);
         v_sales_district varchar2(10);
         v_salesoff varchar2(10);
         v_custgrp varchar2(10);
         v_salesgrp varchar2(10);
    v_type varchar2(20);
    v_nature varchar2(10);
    v_partner_code varchar2(10);
    v_parent_cust varchar2(20);
    v_credit_blk varchar2(20);
    BEGIN
    open c1;
    loop
    fetch c1 into v_cust_cur;
    exit when c1%NOTFOUND;
    for i in (SELECT customer_code, salesorg from load_cust_partner
    where customer_code = v_cust_cur.customer_code ) LOOP
    dbms_output.put_line(v_cust_cur.customer_code );
                        SELECT partner_code into v_partner_code from load_cust_partner
    where customer_code = i.customer_code and salesorg = i.salesorg and partner_function = 'Z1';
    dbms_output.put_line(v_partner_code||i.customer_code);
    SELECT salesorg, sales_district, salesoff, salesgrp, custgrp INTO v_salesorg, v_sales_district, v_salesoff, v_salesgrp, v_custgrp FROM load_cust_sales_area
              WHERE customer_code = i.customer_code and salesorg = i.salesorg;
                   dbms_output.put_line(v_salesorg||i.salesorg);
                        SELECT parent_customer INTO v_parent_cust from load_cust_hierarchy
    WHERE customer_code = i.customer_code and salesorg = i.salesorg and hierarchy_type = 'G'; dbms_output.put_line(v_parent_cust);
                        SELECT credit_block INTO v_credit_blk from load_cust_company_cod
              WHERE customer_code = i.customer_code;
    dbms_output.put_line(v_credit_blk);
    for j in (SELECT account_group, customer_type from load_cust_general
    where customer_code IN (select customer_code from load_cust_partner
                                  where partner_code = i.customer_code and salesorg = i.salesorg and partner_function = 'ZS'))
                                                      LOOP
    -- exit when j%NOTFOUND;
         dbms_output.put_line(j.account_group);
    if (j.account_group = 'ZDIS') THEN
    v_type := 'DISAC';
              v_nature := '06';
         --     EXIT ;
    else
    v_type := 'SPACC';
    v_nature := '01';
    END IF;
    dbms_output.put_line(v_type||' '||v_nature);
    END LOOP;
    INSERT INTO sfdc_account
              (SAP_ACCOUNT_ID__C, NAME, TYPE, RECORDTYPEID, PARENTID, PHONE, FAX, WEBSITE, OWNERID, MARKETING_DOMAIN__C,
    INDUSTRIAL_SECTOR__C, ABC_CLASSIFICATION__C, NAME_1__C, NAME_2__C, NAME_3__C, NAME_4__C, PAYMENT_STATUS__C,
    CUSTOMER_GROUP__C, ADDRESS_STREET__C, CITY__C, POSTAL_CODE__C, COUNTRY__C, SALES_OFFICE__C, SALESORG__C,
    SALESDISTRICT__C, SALESGROUP__C, NATURE__C, VATCODE__C)
    VALUES((i.customer_code||i.salesorg), (v_cust_cur.Name1||' '||v_cust_cur.name2), ' ', v_type, v_parent_cust,
    v_cust_cur.phone_number, v_cust_cur.fax, v_cust_cur.web_address, v_partner_code, SUBSTR(v_cust_cur.industry_sector,1,2),
    v_cust_cur.industry_sector, v_cust_cur.customer_profile, v_cust_cur.name1, v_cust_cur.name2, v_cust_cur.name3,
    v_cust_cur.name4, v_credit_blk, v_custgrp, v_cust_cur.address, v_cust_cur.city, v_cust_cur.postal_code,
    v_cust_cur.country_key, v_salesoff, v_salesorg, v_sales_district,
    v_salesgrp, v_nature, v_cust_cur.vat_code);
    end loop;
    end loop;
    CLOSE c1;
    -- Delete data from Load Table
    -- EXECUTE IMMEDIATE 'TRUNCATE TABLE load_cust_general';
    /* truncate table load_cust_partner;
    truncate table load_cust_hierarhy;
    truncate table load_cust_sales_area;
    truncate table load_cust_company_cod;
    commit;
    exception
    when others then
    raise_application_error( -20001, substr( sqlerrm, 1, 150 ) );
    END;
    Kindly Help.....
    Thanks and Regards

    Create the procedure again and execute it in SQL*Plus environment and paste the output:
    CREATE OR REPLACE procedure insert_sfdc_account
    as
    --DECLARE
    CURSOR C1 IS
    SELECT customer_code, name1, name2, name3, name4, phone_number, fax, web_address, industry_sector, customer_profile, customer_type,
    address, city, postal_code, country_key, zzcust_type, vat_code
    FROM load_cust_general
    WHERE account_group = 'ZSIT';
    v_cust_cur c1%ROWTYPE;
    -- type sales_tab is table of load_cust_sales_area%rowtype;
    v_sales_area load_cust_sales_area%ROWTYPE;
    -- v_sales_area sales_tab;
    v_salesorg varchar2(10);
    v_sales_district varchar2(10);
    v_salesoff varchar2(10);
    v_custgrp varchar2(10);
    v_salesgrp varchar2(10);
    v_type varchar2(20);
    v_nature varchar2(10);
    v_partner_code varchar2(10);
    v_parent_cust varchar2(20);
    v_credit_blk varchar2(20);
    BEGIN
    open c1;
    loop
    fetch c1 into v_cust_cur;
    exit when c1%NOTFOUND;
    for i in (SELECT customer_code, salesorg from load_cust_partner
    where customer_code = v_cust_cur.customer_code ) LOOP
    SELECT partner_code into v_partner_code from load_cust_partner
    where customer_code = i.customer_code and salesorg = i.salesorg and partner_function = 'Z1';
    SELECT salesorg, sales_district, salesoff, salesgrp, custgrp INTO v_salesorg, v_sales_district, v_salesoff, v_salesgrp, v_custgrp FROM load_cust_sales_area
    WHERE customer_code = i.customer_code and salesorg = i.salesorg;
    dbms_output.put_line('Customer_Code : '|| i.customer_code);
    dbms_output.put_line('SalesOrg : '|| i.salesorg);
    SELECT parent_customer INTO v_parent_cust from load_cust_hierarchy
    WHERE customer_code = i.customer_code and salesorg = i.salesorg and hierarchy_type = 'G';
    dbms_output.put_line('Successfully Executed SQL st. Error is somewhere else');
    SELECT credit_block INTO v_credit_blk from load_cust_company_cod
    WHERE customer_code = i.customer_code;
    for j in (SELECT account_group, customer_type from load_cust_general
    where customer_code IN (select customer_code from load_cust_partner
    where partner_code = i.customer_code and salesorg = i.salesorg and partner_function = 'ZS'))
    LOOP
    -- exit when j%NOTFOUND;
    if (j.account_group = 'ZDIS') THEN
    v_type := 'DISAC';
    v_nature := '06';
    -- EXIT ;
    else
    v_type := 'SPACC';
    v_nature := '01';
    END IF;
    END LOOP;
    INSERT INTO sfdc_account
    (SAP_ACCOUNT_ID__C, NAME, TYPE, RECORDTYPEID, PARENTID, PHONE, FAX, WEBSITE, OWNERID, MARKETING_DOMAIN__C,
    INDUSTRIAL_SECTOR__C, ABC_CLASSIFICATION__C, NAME_1__C, NAME_2__C, NAME_3__C, NAME_4__C, PAYMENT_STATUS__C,
    CUSTOMER_GROUP__C, ADDRESS_STREET__C, CITY__C, POSTAL_CODE__C, COUNTRY__C, SALES_OFFICE__C, SALESORG__C,
    SALESDISTRICT__C, SALESGROUP__C, NATURE__C, VATCODE__C)
    VALUES((i.customer_code||i.salesorg), (v_cust_cur.Name1||' '||v_cust_cur.name2), ' ', v_type, v_parent_cust,
    v_cust_cur.phone_number, v_cust_cur.fax, v_cust_cur.web_address, v_partner_code, SUBSTR(v_cust_cur.industry_sector,1,2),
    v_cust_cur.industry_sector, v_cust_cur.customer_profile, v_cust_cur.name1, v_cust_cur.name2, v_cust_cur.name3,
    v_cust_cur.name4, v_credit_blk, v_custgrp, v_cust_cur.address, v_cust_cur.city, v_cust_cur.postal_code,
    v_cust_cur.country_key, v_salesoff, v_salesorg, v_sales_district,
    v_salesgrp, v_nature, v_cust_cur.vat_code);
    end loop;
    end loop;
    CLOSE c1;
    -- Delete data from Load Table
    -- EXECUTE IMMEDIATE 'TRUNCATE TABLE load_cust_general';
    /* truncate table load_cust_partner;
    truncate table load_cust_hierarhy;
    truncate table load_cust_sales_area;
    truncate table load_cust_company_cod;
    commit;
    exception
    when others then
    raise_application_error( -20001, substr( sqlerrm, 1, 150 ) );
    END;
    SQL> set serveroutput on
    SQL> exec insert_sfdc_account;

  • Resolved: Use value from select list in pl/sql block

    Hello,
    I have a form with a select list: P18_BONUSTYPE, the values of which come from a LOV.
    When the user clicks a button, a page process is used to insert a row into a table.
    When I use the :P18_BONUSTYPE bind variable in my insert statement I get an error "Invalid number" I get an "Invalid number" error. I assume that APEX is using the displayed text in that bind variable, not its actual (html option) value.
    I checked the HTML of the page, and the correct values are in the select list.
    Can someone tell me how to get the value into a bind variable that can be used in a pl/sql block for a page process?
    Thanks
    Message was edited by:
    Neeko
    Issue was a value in another item.

    Did you tried changing the value using "to_number"? (i.e. to_number(:P18_BONUSTYPE)).
    Max.

  • How to compare dates in a select query in open sql

    Hi
                       How can I retrieve data pertaining to a specified date using a select query.
    I have inserted date using the following code:
    String dateString = "2009-03-11";
    java.sql.Date date = java.sql.Date.valueOf(dateString);
    PreparedStatement stmt =con.prepareStatement("insert into DATEACCESS"
                                                                            + "(DATETEST)"
                                                                            + "values (?)");
    stmt.setDate(1,date);
    stmt.executeUpdate();
    How can I pass this in a select query,the below mentioned query did not fetch me any results.
    Select * from  DATEACCESS where DATETEST='2009-03-11'

    Hi
    Has ur date  problem resolved  ?
    If not resolved u can do the following
    As u already have sql date today declared . You want to get the data depending on that date
    As ur query is
    if( today != null)
    String query2 = select * from DATEACCESS where DATETEST<= ?
    PreparedStatement ps = conn.prepareStatement(query2);
    ps.setDate(1,today)
    ResultSet rs = ps.executeQuery();
    While(rs.next)
        ////// Here u will get data from query u needed ///
    If this also does not work just print the date and check in which format is it returning u .
    Regards
    Anuradha Rao
    Edited by: Anuradha Rao on Mar 20, 2009 10:16 AM

  • DDL inside PL/SQL Block

    Is there anyone knows if DDL statement can be include inside the PL/SQL block?
    I mean, creating a table, doing DML in that table and then dropping it? I have to do this because I'm having integrity constraint errors (ORA-02291) in the tables I will use.
    I need to
    update table_1 set id = 2 where id = 1
    but it it found child records in table_2.
    when i tried:
    update table_2 set id = 2 where id = 1
    Of course I cannot as well update table_2 because it will not found parent record in table_1, as it had an error earlier and there were more records in table_1 than table_2.
    table_1 records = 374 rows
    table_2 records = 38 rows
    I did some strange logic below:
    a. Creating a temporary table,
    b. inserting there records in table_1,
    c. updating the temp table,
    d. delete the records i got in table_1,
    e. update table_2 (can now do an update since no child records in table_1 will be found after the delete),
    f. insert records from temp table to table_1
    g. drop the temp table.
    BUT, I cannot create, manipulate, and drop that temp table inside the PL/SQL table.
    Any thoughts.
    Thanks in advance!

    Another scenario is to create your constraints as deferred. I'v recently blogged about another deferred constraint usage here
    http://gplivna.blogspot.com/2007/05/deferred-constraint-real-life-scenario.html
    but your case also is appropriate.
    But the ultimate problem BTW is that you need to update your PK values and that's at least very questionable (ok to my mind bad) design.
    Gints Plivna
    http://www.gplivna.eu

  • Unable to set count for Select Query for BizTalk SQL receive port

    Hi All,
    Iam using BizTalk server 2009 classic SLQ adapter (using XML clause)for my integration to pull records from DB in to my application.
    As per the DB values iam unable to set the record count as this started giving me error below (first it worked for 820 records with select Query.and then 400 and going down with respect to multiple runs).Kindly help .
    Thanks in advance.

    Hi Abhishek,
    iam still getting the same error for 1000 records.
    after turning off PreserveBOM aswell in send pipeline.
    There was a failure executing the receive pipeline: "Microsoft.BizTalk.DefaultPipelines.XMLReceive, Microsoft.BizTalk.DefaultPipelines, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Source: "Pipeline " Receive Port:
    "SQLPort" URI: "SQL://XXXXX/OneC_DB/" Reason: An error occurred when parsing the incoming document: "'
    ', hexadecimal value 0x0B, is an invalid character. Line 188, position 3944.". 

  • CASE INSIDE PL/SQL BLOCK

    Hi,
    Im executing a procedure with a dynamic sql query,
    inside the dynamic query there is a case statement:
    (CASE
               WHEN m.sender is not null
                  THEN ''PULL_PUSH''
               ELSE ''NOT PULL_PUSH''
            END
           ) download_type,and the server gives me the next error:
    ORA-00904: downloadtype: invalid identifier tips_
    what can I do to change the "is not null " comparision?
    Thanks in advanded...

    IF PULL_PUSH and NOT PULL_PUSH are parameters or variables then you might have to add || So, the code will look something like
    (CASE
               WHEN m.sender is not null
                  THEN ' || PULL_PUSH || '
               ELSE  NOT ' ||  PULL_PUSH || '
            END
           ) download_type,But this is just a wild assumption,
    And as Karthick, said it will be beneficial if you provide the complete query for more analysis.

  • Single select query or any sql statement with o/p

    Hi,
    I have one table test_tab with column names empno,empname.The test_tab values is as follows,
    empno empname
    01 siva
    02 ram
    03 kamal
    04 sathish
    i will give the empname values like 'siva,kamal,roshan,sathish' and empno >03,but in the table roshan name is not there.I need the below mentioned o/p
    example qry: select empno,empname from test_tab where empname in('siva','kamal','roshan','sathish') and empno>03;
    my o/p should be like this,
    empname empno
    sathish 04
    roshan ''
    But the empname 'roshan' is not there in table.I need the empname as 'roshan' and empno is null value in a single select query or subquery or any sql statements.
    Please help me the resolve this issue.
    Thanks
    Sivaraman

    Hi,
    Do you want this?
    with data as
    (select 1 EMPNO, 'siva' as empname from  DUAL union all
    select 2 EMPNO, 'ram' from  DUAL union all
    select 3 EMPNO, 'kamal' from  DUAL union all
    select 4 EMPNO, 'sathish' from  DUAL union all
    select null EMPNO, 'roshan' from  DUAL )
    select *  from data
    where EMPNAME in ('siva','kamal','roshan','sathish')
       and nvl2(empno,empno,4) > 3 

  • My First while loop inside PL/SQL block not working , please help

    Hi ,
    I am new to PL/sql and struck at PL SQL blocks , please help to solve this .
    declare
    v_A number constant :=10 ;
    j number constant := 3 ;
    BEGIN
    WHILE j < v_A
    LOOP
    DBMS_OUTPUT.PUT_LINE('Hai');
    END LOOP;
    END;
    please help as how to resolve this .
    Thanks in advance .

    btw it's a useful habit to use indentation to highlight the block structure. Also it's worth deciding what your convention will be for keywords (I use uppercase, lowercase is also fine as far as I'm concerned but I've set up my editor to uppercase them) and variables, database object names etc (I use lowercase), e.g:
    DECLARE
       v_a CONSTANT PLS_INTEGER := 10;
       j   CONSTANT PLS_INTEGER := 3;
       i PLS_INTEGER := j;
    BEGIN
       WHILE i <= v_a LOOP
          DBMS_OUTPUT.PUT_LINE(i);
          i := i +1;
       END LOOP;
    END;or perhapsdeclare
       v_a constant pls_integer := 10;
       j   constant pls_integer := 3;
       i pls_integer := j;
    begin
       while i <= v_a loop
          dbms_output.put_line(i);
          i := i +1;
       end loop;
    end;When I see "declare" and "BEGIN" in the same block of code I worry about the standard of code I'm going to see...

  • Select query in Advanced SQL Filter

    Hi All
    I am creating a shared filter and I need to write an sql statement for a column. Can I use
    string functions in the Advanced SQL Filter. My sql query is :
    select distinct "Exchange Rate"."Type" from "Credit"
    where substr(rtrim("Exchange Rate"."Type"),-1,2) in (select distinct substr(rtrim( "-Year"."Year Name"),-1,2)
    from "Credit" where CURRENT_DATE between "-Year"."Year Start Date" and "-Year"."Year End Date" )
    where, "Credit" = Name of the subject area
    "Exchange Rate" and "-Year"= presentation tables
    I'm getting the error:
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 27002] Near <select>: Syntax error [nQSError: 26012] . (HY000)
    I then tried a simple query in the Advanced SQL Filter: "Exchange Rate"."Type" = SELECT "Exchange Rate"."Type" FROM "Credit"
    which does not work either.
    Can't seem to debug the problem.
    Thanks

    Hi user770000,
    How did you resolve the issue. I am trying to use the sql query in the filter and getting same error as yours.
    Here is the advanced SQL of the filter condition
    CAST("ARRA Financial Weekly Report"."DW Updated" AS DATE) = SELECT MAX(CAST("ARRA Financial Weekly Report"."DW Updated" AS DATE)) from "ARRA Recovery Act Status"
    When I issue following sql in direct sql, it returns required value
    SELECT MAX(CAST("ARRA Financial Weekly Report"."DW Updated" AS DATE)) from "ARRA Recovery Act Status"

  • BULK COLLECT in select query inside a function

    Hi All,
    My query is :
    SELECT col1,col2,col3 FROM table_a; --( consider this is a long running query with lot of joins)
    Need to know how can i get the output of the above query from a function using BULK COLLECT.
    and i tried this:
    CREATE OR REPLACE TYPE tab_a_row
    AS OBJECT (
    col1 number(20),
    col2 number(20),
    col2 number(20)) ;
    create or replace type tab_a_nt as table of tab_a_row;
    create or replace function get_table_a
    return sys_refcursor
    is
    tab_a_recs tab_a_nt;
    rv sys_refcursor;
    begin
    SELECT tab_a_row(col1,col2,col3) BULK COLLECT INTO tab_a_recs FROM table_a;
    open rv for select * from table(tab_a_recs);
    return rv;
    end;
    Function created successfully. and i exec this from sql plus using
    SQL> var rc refcursor;
    SQL> exec :rc := get_table_a;
    BEGIN :rc := get_table_a; END;
    ERROR at line 1:
    ORA-22905: cannot access rows from a non-nested table item
    ORA-06512: at "GET_TABLE_A", line 12
    ORA-06512: at line 1
    Kindly share your ideas on how to use bulk collect and get set of outputs from a function.
    Edited by: 887268 on Apr 18, 2013 3:10 AM

    >
    If i use refcursor , then the JAVA code needs to be changed accordinglyto get the refcursor output.
    >
    Well, of course. Java has to know what the sql projection is. How else will it know how many columns there are and their datatypes.
    But that is true no matter what method you use.
    >
    But if i use a PLSQL COLLECTION TYPE (nested tables ) , then i can get output as ,
    select * from table(function_name(input1,input2));
    >
    No - using the 'table' function mean you are calling a PIPELINED function.
    This is a sample of a PIPELINED procedure.
    -- type to match emp record
    create or replace type emp_scalar_type as object
      (EMPNO NUMBER(4) ,
       ENAME VARCHAR2(10),
       JOB VARCHAR2(9),
       MGR NUMBER(4),
       HIREDATE DATE,
       SAL NUMBER(7, 2),
       COMM NUMBER(7, 2),
       DEPTNO NUMBER(2)
    -- table of emp records
    create or replace type emp_table_type as table of emp_scalar_type
    -- pipelined function
    create or replace function get_emp( p_deptno in number )
      return emp_table_type
      PIPELINED
      as
       TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE;
        emp_cv EmpCurTyp;
        l_rec  emp%rowtype;
      begin
        open emp_cv for select * from emp where deptno = p_deptno;
        loop
          fetch emp_cv into l_rec;
          exit when (emp_cv%notfound);
          pipe row( emp_scalar_type( l_rec.empno, LOWER(l_rec.ename),
              l_rec.job, l_rec.mgr, l_rec.hiredate, l_rec.sal, l_rec.comm, l_rec.deptno ) );
        end loop;
        return;
      end;
    select * from table(get_emp(20))Or your function could return a collection like the example from this thread this morning.
    Example of Collection as datatype of a function’s return value
    CREATE OR REPLACE TYPE enamelist as VARRAY(20) of VARCHAR2(20)
    /* Formatted on 4/18/2013 4:06:47 PM (QP5 v5.126.903.23003) */
    CREATE OR REPLACE FUNCTION ename_fn
    RETURN enamelist
    AS
    v_cursor_main enamelist := enamelist ();
    BEGIN
    SELECT ename
    BULK COLLECT
    INTO v_cursor_main
    FROM emp;
    RETURN v_cursor_main;
    EXCEPTION
    WHEN OTHERS
    THEN
    RETURN v_cursor_main;
    END;
    select * from table(ename_fn()) from dual;
    COLUMN_VALUE
    SMITH
    ALLEN
    WARD
    JONES
    MARTIN
    BLAKE
    CLARK
    SCOTT
    KING
    TURNER
    ADAMS
    JAMES
    FORD
    MILLER

  • Running a Select query against multiple sql servers using SSIS script task.

    Hi Guys,
    I need to fetch data from multiple sql servers using  SSIS scirpt task inside a foreach container.
    is there anyway i can build dynamic sql connections using ssis variables inside SSIS script task in each loop
    Please guide me or refer any blogs so that i will try..
    Thanks in advance.

    Your only options is using .net code, then it will be no different than using a console app in a loop.
    using (SqlConnection connection = new SqlConnection(connectionString))
    connection.Open();
    Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
    Console.WriteLine("State: {0}", connection.State);
    and so forth for each connection string
    the connection string would come from the ForEach loop
    Arthur My Blog

  • Problem with select query inside a function.

    Hi,
    i have created a function as
    create or replace function "NEW"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    select sum(allocation_percent) into v_alo from employeeproject where start_date < s_date and end_date > e_date and pid != 'BPDE-KER12' and employee_id = emp;
    select allocation_percent into v_alo2 from employeeproject where start_date < s_date and end_date > e_date and pid = 'BPDE-KER12' and employee_id = emp;
    select max(end_date) into v_date from employeeproject where employee_id=emp having max(end_date) <= S_DATE;
    if v_alo < 100 then
    return 1;
    else if v_alo2 = 100 then
    return 2;
    else if v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    end if;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;it is compiled correctly.
    when executing the function with
    select abc.a,new(a,'03-jan-2011','04-jan-2011') "status" from abc where new(a,'03-jan-2011','04-jan-2011') in (1,2,3,4);it is returning
    A status
    1 5
    2 5
    3 5
    instead of
    A status
    1 1
    2 2
    3 3
    and when i comment any two select statements then some part of my ans is correct.
    unable to understand the behaviour.
    can any pls help me understand it.
    Thanks,
    hari

    Hi,
    thanks for the reply, and sorry for my ugly code.
    i am using Oracle database 10g express edition.
    Case could be a option to use but i need to figure why my query is not returning any value when used together.
    my requirement is to find
    the employees who are have allocation percent sum < 100 for a defined period(excluding pid=BPDE-KER12) and
    employee who is mapped to pid=BPDE-KER12 not in my first requirement in that period and
    the employees whose latest end date is less than the new start date.
    i have tried the new modified code as you said but this time it returns null, not even exceptions running.
    i divide my requirement into three functions which will return value.
    1.  create or replace function "NEW4"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    --to check if the employee total percentage is <100 then return 1 else return 4
    select sum(allocation_percent) into v_alo from pm_employee_project
    where
    start_date < s_date and end_date > e_date and pid !='BPDE-KER12' and employee_id = emp;
    if v_alo < 100 then
    return 1;
    elsif v_alo2 = 100 then
    return 2;
    elsif v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;
    then,
    select abc.a,NEW4(a,'03-jan-2011','30-jan-2011') "STATUS" from abc
    result,
    A STATUS
    1 *1*
    2 4
    3 4 2.create or replace function "NEW5"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    --To select employee who are in a specific pid.
    select allocation_percent into v_alo2 from pm_employee_project where
    start_date < s_date and end_date > e_date and pid = 'BPDE-KER12' and
    employee_id = emp;
    if v_alo2 = 100 then
    return 2;
    elsif v_alo < 100 then
    return 1;
    elsif v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;
    then,
    select abc.a,NEW5(a,'03-jan-2011','30-jan-2011') "STATUS" from abc
    Result,
    A STATUS
    1 5
    2 *2*
    3 5 3.   create or replace function "NEW6"
    (emp in number,
    s_date in DATE,
    e_date in DATE)
    return number
    is
    v_alo number default 0;
    v_alo2 number default 0;
    v_date date;
    begin
    --to select the employee whose project end date is less thann the new date.
    select max(end_date) into v_date from pm_employee_project where
    employee_id=emp having max(end_date) <= S_DATE;
    if v_alo2 = 100 then
    return 2;
    elsif v_alo = 100 then
    return 1;
    elsif v_date < s_date then
    return 3;
    else
    return 4;
    end if;
    exception
    when NO_DATA_FOUND then
    return 5;
    end;
    then,
    select abc.a,NEW6(a,'03-jan-2011','30-jan-2011') "STATUS" from abc
    Result,
    A STATUS
    1 5
    2 5
    3 *3* so my function works properly individually, but i want all the three conditions in a single function with same order as above 1 then 2 and then 3.
    and when i try to do it that way i am not getting my result as
    A STATUS
    1 *1*
    2 *2*
    3 *3*
    so how can i proceed.
    my input table values,
    select * from abc
    A B C
    1 2 2
    2 1 3
    3 1 2
    select * from pm_employee_project
    varchar2 varchar2 date date date varchar2
    EMPLOYEE_ID PID START_DATE END_DATE ALLOCATION_PERCENT SUPERVISOR_ID
    1 10 02-JAN-11 31-JAN-11 89 -
    1 20 05-JAN-11 20-JAN-11 9 -
    1 BPDE-KER12 21-JAN-11 31-JAN-11 11 -
    2 BPDE-KER12 01-JAN-11 31-JAN-11 100 -
    3 30 01-JAN-10 01-JAN-11 100

  • A question about input values inside PL/SQL block

    Dear all,
    I would appreciate if you could kindly help me with this question.
    Consider the following code.
    DECLARE
      myvar1 NUMBER;
      myvar2 NUMBER;
      myvar3 NUMBER;
    BEGIN
      myvar1 := &1;
      myvar2 := &2;
      myvar3 := &3;
      DBMS_OUTPUT.put_line('myvar1 = ' || myvar1);
      DBMS_OUTPUT.put_line('myvar2 = ' || myvar2);
      DBMS_OUTPUT.put_line('myvar3 = ' || myvar3);
    END;
    /This program reads three values as input and prints them. However, I noticed that if instead of writing
    myvar1 := &1;
    myvar2 := &2;
    myvar3 := &3;I write
    myvar1 := '&1';
    myvar2 := '&2';
    myvar3 := '&3';The program will have very same result. I would like to know whether there is a semantic difference between both syntax,
    that is, is there any difference between for example &myvar1 and 'myvar1'?
    Thanks in advance,
    Dariyoosh

    Try this
    CREATE TABLE test_sem  (x VARCHAR2(10), y NUMBER)
    INSERT INTO test_sem VALUES ('A',1);
    INSERT INTO test_sem VALUES ('B',1);
    INSERT INTO test_sem VALUES ('C',1);
    INSERT INTO test_sem VALUES ('D',1);
    SELECT * FROM test_sem WHERE x='&1' --OK
    SELECT * FROM test_sem WHERE x=&1 -- error not a valid number
    SELECT * FROM test_sem WHERE y=&1 -- ok
    SELECT * FROM test_sem WHERE y='&1' -- ok since numbers can be converted to strings'&1' is for characters &1 for numbers;
    You can verify form above test case
    Regards,
    Bhushan

Maybe you are looking for