Oracle Function with a select into problem

Here is one that I cannot figure out. I'm trying to select the median of a set of events in a purchase qty. I have the selects working in SQL. It returns the correct answer for several sets of test data. However, when I put this into a function to be able to call during more complex queries it doesn't work. I've tested the function several different ways and it's looking like the select median into v_median2... is not working. Please help!
Here is the code... When this is run what ever is in v_plant is returned. IE: If you pass 1122 into with getmedian('4567','12345678-0001') this returns 4567 at the output. I've bypassed the v_plant and v_material in the select part below and it still output 4567.
If you run the select (with test data put in place of v_plant and v_material in a sqlplus window without the INTO v_median2) it would return a 12.
If you run this function as is it would return 4567.
Here is the output from the dbms_output tests.
4567
12345678-0001
4567
12345678-0001
4567
WHY?
CREATE OR REPLACE FUNCTION getmedian(v_plant IN VARCHAR2, v_material IN VARCHAR2)
RETURN NUMBER
AS
v_median2 NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE(v_plant);
DBMS_OUTPUT.PUT_LINE(v_material);
SELECT MEDIAN INTO v_median2
FROM (SELECT ROWNUM as rownums,MEDIAN
FROM (SELECT abs(quantity_in_unit_entry) AS MEDIAN
FROM tbl_transactions
WHERE plant = v_plant
AND material = v_material
AND movement_type IN ('961','261','201')
ORDER BY quantity_in_unit_entry DESC))
WHERE ROWNUMs = ( select round(COUNT(1)/2,0) AS TOTAL2
from tbl_transactions t
WHERE plant = v_plant
AND material = v_material
AND t.movement_type IN ('961','261','201'));
DBMS_OUTPUT.PUT_LINE(v_plant);
DBMS_OUTPUT.PUT_LINE(v_material);
DBMS_OUTPUT.PUT_LINE(v_median2);
RETURN v_median2;
END;

It looks like another one of those cases where the pl/sql engine doesn't yet handle everything that the sql engine does. The usual solution is to execute the part that only works in sql dynamically. Try this:
CREATE OR REPLACE FUNCTION getmedian
  (v_plant    IN VARCHAR2,
   v_material IN VARCHAR2)
  RETURN         NUMBER
AS
  v_rownums      NUMBER          := 0;
  v_sql          VARCHAR2 (4000) := NULL;
  v_median2      NUMBER          := 0;
BEGIN
  SELECT ROUND (COUNT (1) / 2, 0)
  INTO   v_rownums
  FROM   tbl_transactions
  WHERE  plant = v_plant
  AND    material = v_material
  AND    movement_type IN
         ('961', '261', '201');
  v_sql :=
  'SELECT median
   FROM   (SELECT ROWNUM AS rownums,
                  median
           FROM   (SELECT   ABS (quantity_in_unit_entry)
                                AS median
                   FROM     tbl_transactions
                   WHERE    plant = :v_plant
                   AND      material = :v_material
                   AND      movement_type IN
                            (''961'', ''261'', ''201'')
                   ORDER BY quantity_in_unit_entry DESC))
   WHERE  rownums = :v_rownums';
  EXECUTE IMMEDIATE v_sql INTO v_median2
  USING v_plant, v_material, v_rownums;
  RETURN v_median2;
END getmedian;

Similar Messages

  • I can't execute oracle functions with c#.  i'm using oracle 9i version.

    i have a problem trying to execute an oracle function with c#.net. The Oracle version i'm using is Oracle 9i.
    This is the function definition: (it's defined and working right because i have tryed it with SQLWorksheet)
    CREATE OR REPLACE Function NRegistros return integer is
    Numero integer(4);
    begin
    select count(*) into Numero from singles;
    return Numero;
    END NRegistros;
    But with c#.Net i can't acces it because i get an error: "this is not a procedure or is not defined". And i think the code is right. In fact in the same code you can see that i'm using an stored procedure and i have not problems. But with the function i have problems. Is it possible that "OracleClient" can't work with Oracle9i functions??. This is the code:
    OracleParameter Parametro = new OracleParameter("Name", OracleType.VarChar,10);
    OracleParameter ParametroFuncion = new OracleParameter("Retorno", OracleType.Int32, 4);
    Parametro.Direction = ParameterDirection.Output;
    ParametroFuncion.Direction = ParameterDirection.ReturnValue;
    OracleConnection Conexion = new OracleConnection("Data Source=DISCOS;User Id=SYSTEM;Password=a0000;");
    Conexion.Open();
    OracleCommand Todos = new OracleCommand();
    OracleCommand Procedimiento = new OracleCommand();
    OracleCommand Funcion = new OracleCommand();
    Todos.Connection = Conexion;
    Todos.CommandType = CommandType.Text;
    Todos.CommandText="select * from singles";
    Procedimiento.Connection = Conexion;
    Procedimiento.CommandType = CommandType.StoredProcedure;
    Procedimiento.CommandText = "Procedimiento";
    Procedimiento.Parameters.Add(Parametro);
    Funcion.Connection = Conexion;
    Funcion.CommandType = CommandType.StoredProcedure;
    Funcion.CommandText = "NRegistros";
    OracleDataReader Lector = Todos.ExecuteReader();
    BindingSource Discos = new BindingSource();
    Discos.DataSource = Lector;
    dgvSingles.DataSource = Discos;
    Procedimiento.ExecuteNonQuery();
    Funcion.ExecuteNonQuery();
    lblRegistroProcedimiento.Text = Procedimiento.Parameters["Name"].Value.ToString();
    lblNregistros.Text=Funcion.Parameters["Retorno"].Value.ToString();
    Conexion.Close();
    Edited by: user11921281 on 22-nov-2009 20:32

    thank you very much. It was a stupid error, sorry. There was one line left :
    OracleParameter Parametro = new OracleParameter("Name", OracleType.VarChar,10);
    OracleParameter ParametroFuncion = new OracleParameter("Retorno", OracleType.Int32, 4);
    Parametro.Direction = ParameterDirection.Output;
    ParametroFuncion.Direction = ParameterDirection.ReturnValue;
    OracleConnection Conexion = new OracleConnection("Data Source=DISCOS;User Id=SYSTEM;Password=a0000;");
    Conexion.Open();
    OracleCommand Todos = new OracleCommand();
    OracleCommand Procedimiento = new OracleCommand();
    OracleCommand Funcion = new OracleCommand();
    Todos.Connection = Conexion;
    Todos.CommandType = CommandType.Text;
    Todos.CommandText="select * from singles";
    Procedimiento.Connection = Conexion;
    Procedimiento.CommandType = CommandType.StoredProcedure;
    Procedimiento.CommandText = "Procedimiento";
    Procedimiento.Parameters.Add(Parametro);
    Funcion.Connection = Conexion;
    Funcion.CommandType = CommandType.StoredProcedure;
    Funcion.CommandText = "NRegistros";
    Funcion.Parameters.Add(ParametroFuncion); //<--------------------- That one !!! (yes it was a stupid error jeje)
    OracleDataReader Lector = Todos.ExecuteReader();
    BindingSource Discos = new BindingSource();
    Discos.DataSource = Lector;
    dgvSingles.DataSource = Discos;
    Procedimiento.ExecuteNonQuery();
    Funcion.ExecuteNonQuery();
    lblRegistroProcedimiento.Text = Procedimiento.Parameters["Name"].Value.ToString();
    lblNregistros.Text=Funcion.Parameters["Retorno"].Value.ToString();
    Conexion.Close();

  • Debug an oracle function with toad 7.4, oracle 9i

    Hello,
    i wanna debug an oracle function with toad 7.4
    so i wanna give param to this function and fix breakpoint and verfy some variables values ... etc
    could you show me how debug it?
    Thanks
    Regards
    Elyes

    Do you have the Toad Debugger? Thats the extra cost option which you get for free in OracleSqlDeveloper.
    If you have the ToadDebugger, Read the Manual
    If not , download OracleSqlDeveloper and use it. It's free, and written by Oracle.

  • Oracle Function with out parameters

    Hi, I'm trying to access a stored function on an oracle server with 2 out parameters, 2 in parameters and an out ref cursor.
    PL/SQL looks like this
    nStatusCode OUT INTEGER,
    sStatusMsg OUT VARCHAR2,
    sUsrNr           IN VARCHAR2,
    sPassword           IN VARCHAR2,
    crsReturn OUT pck_cursor.retRecordSet
    I drag the function onto dataset designer and it successfully maps the results to the datatable, it maps datatypes for first out parameters to decimal and string.
    the method genearated for fill by looks like (out decimal?,out string,string, string, out object)
    problem is, everytime i try to call this function it gives me casting exceptions for the first 2 out parameters, for the decimal it's not specified in more detail. for the other one it says there was an exception casting from OracleString to string. If I change the PL/SQL function to leave the first 2 out parameters away it works fine. Do I manually need to change the TableAdapter definitions??

    Hi,
    I think I found the problem but not a good solution. It seems to be a problem with auto code generation for TableAdapters in the Dataset wizard. In the Parameter Definition for the Command I set DbType.Decimal and DbType.Sting for the SqlDbtype Property of the out params. The GetData and Fill Method is generated with Fill(out decimal? out1, out string out2). When I look in the generated code ith first sets the SqlDbtype as written but after this also the OracleDbtype to OracleDbType.Decimal and OracleDbType.Varchar2. The casting these types before returning the throws the exception. Any idea how to change this behavior?

  • Union  dataset from oracle function with dataset from a postgres function

    I retrieve two sets of data,
    one from an oracle database using  Command_1    select * from  table(functionname(param1, param2))
    one from postgres database using  Command_2     select * from  functionname(param1, param2)
    i can join  the two tables (Command_1 and Command_2) with database expert > links
    I would like to know if it is possible to UNION the two sets

    Don't think so.
    I have only done that by linking from Oracle to the other database and forming the union in Oracle.
    Ian

  • Oracle functions with PowerPivot

    Hi All,
    I have a requirement of building reports using Oracle functions in PowerPivot.
    I have tried using Table Import Wizard and Command Type=StoredProcedure in th ePowerPivot.
    Any help will be appreciated.
    Thanks and Regards,
    SS

    Hello,
    I don't think we can use Oracle functions/stored procedures in PowerPivot, please see the similar thread below:
    http://social.technet.microsoft.com/Forums/en-US/22e67f7f-0753-4f21-bae2-1812d2daf03e/powerpivot-oracle-stored-procedure-err-the-sql-statement-is-not-valid-there-are-no-columns?forum=sqlkjpowerpivotforexcel
    I would suggest you elaborate your requirement with more detail.  
    Regards,
    Elvis Long
    TechNet Community Support

  • Copy Function with Single selection of row

    I want to copy necessary Planning items in my Input ready query from period 1 to remaining periods based on variable entries.  To achieve this I have created a copy planning function to copy amount entered in period 1 (variable) to range of posting period variable entries (e.g. 2 -12 or 6-12).
    I have created structure for GL accounts and I want to copy from period 1 to 2 - 12 for one row at a time.
    I have created WAD template, I selected in behavior section of Analysis item, single with command option and assigned Planning sequence (consisting of copy function) as command.
    On execution of WAD, I select single row in my input ready query and instead of one row getting copied over to the range of posting period, all rows consisting of Planning Items with amount are getting copied over, which I am not expecting with single selection option.
    How can I have only one row getting copied over?
    Am I am missing something?
    Your suggestions are highly appreciated.
    Regards,
    Sachin

    Hello Gregor,
    Thanks for your response.  I tried what you have suggested and also followed the documentation, not sure why it is not working as expected
    In my variable I have characterictis such as:
    Version
    Fiscal Year
    Fiscal Year Variant
    Profit Center
    In my rows:
    Planning Item
    Columns:
    Period
    Amount
    In behavior I have selected Row Selection Single.  I am using Button group and assigned following:
    Command: Execute a Planning Function -> In Data Binding -> Selection Binding -> Characteristic -> Planning Item -> Binding Type -> Item Characteristic -> Web Item Selection -> Item Binding -> Query (Analysis Item) -> Characteristic -> Planning item.
    For Variable I have defined nothing.
    Do you think my settings are correct?
    Regards,
    Sachin

  • SELECT * INTO Problem

    I need help, please. I'm trying this basic statement to create a backup copy of the hr.employees table.
    SELECT * INTO employees_Backup FROM employees
    Which I copied from examples on the internet (two sources, same syntax)
    When I run this in SQL Developer, I get the following:
    ORA-00905: missing keyword
    00905. 00000 - "missing keyword"
    *Cause:   
    *Action:
    Error at Line: 1 Column: 14

    Hi,
    Houffle wrote:
    ... Now, if I can just learn to format my code when I post.This site normally doesn't display multiple spaces in a row.
    Whenever you post formatted text (such as query results) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Multiple oracle session with one select

    Hi,
    When i run simple select statment oracle OPENS 5 different sessions and each session run same select .
    any body know what is wrong with it ,is there any parameter problem.
    HERE is a programe :
    ORACLE.EXE (P000)
    ORACLE.EXE (P001)
    ORACLE.EXE (P002)
    ORACLE.EXE (P003)
    ORACLE.EXE (P004)

    Basically my problem is that i am running an INSERT statement based on a SELECT statement on different tables.
    Now the problem is at times Oracle stops responding and my application hangs.
    I cannot find any other clue than the parrallel execution of INSERT statement by ORACLE.
    The reason i am considering this as an issue is when i check the status of my table on which i am running INSERT statement, they are locked.
    Below is sample peusdocode of my task.
    For each file
    begin
    open oracle connection
    read data from file using sql loader;
    insert into my tables based on select; ///// here after reading 1 or 2 files oracle hangs
    close oracle connection;
    end

  • Oracle function to extract data into excel sheet

    I have extracted data from a couple of tables onto a view. Basically I have got about 15 coloums in that view but i need to extract the data in the view into an Excel sheet.
    I just want to know if their is a function in oracle whereby i can export the data in the view onto an excel sheet, because this statements is going to be scripted and run every morning for the data to be processed.
    Oracle version: oracle 9i
    OS : Windows 2003

    There are at least three options.
    One is to use UTL_FILE or spool to write the results out as a comma separated file. Excel can then read the .CSV without a hitch. Only use spool you want to overwrite the file (on create a new one) each day.
    The second approach would still use UTL_FILE but use Tom Kyte's OWA_SYLK utility to write an Excel-readable file.
    The third approach would be to reverse the direction. Define your database as a DNS datasource and embed your query in the Excel spreadsheet. This obviates the need for the user to pfaff around with CSV files but does require a bit more work on the OS side.
    Which approach you choose rather depends upon your precise needs.
    Cheers, APC

  • Arrow keys with direct select tool problem

    Hi list,
    I hope somebody can help me. I just switched from MX to CS3.
    Now selecting an anchor with the direct select tool and
    moving it with
    the arrow keys moves it 30 Steps at once (Using normal select
    tool works
    as usual). Strangely enough I have to undo 30 Times for one
    time hitting
    the arrow key.
    Does anyone know this problem or have a hint where to switch
    this?
    thanks in advance
    oe

    Your frustration is understandable. Anchor point selection is unforgiving in InDesign, especially when compared to Illustrator with Smart Guides, although I wouldn't call it "broken."
    I suspect most InDesign users don't do enough "path editing" on their InDesign pages for there to be an outcry over this.
    Pablo28282 wrote:
    It shouldn't be able to select and move an image. That is not the point of the tool.
    That's always been a function of the Direct Select tool. Simply, if you're aiming for an anchor point and select the frame's content instead, you've missed the point. <rimshot>
    There's nothing broken, and no advice to offer, other than zoom in further, slow down, and keep an eye on the pointer cues which change when the pointer is over an anchor point. I suppose it's also possible you could make adjustments to your mouse/input device settings that might help you move and click more precisely.

  • Executing a oracle function with parameters ...

    Hi All,
    I'm trying to execute this part of the code:
    <cfdirectory action="list"
    directory="#getDirectoryFromPath(sharedPath)#"
    name="currentDir">
    <cfoutput query="currentDir">
    <cfset filename = sharedPath & name>
    <cfif find(".csv",name)>
    <cfexecute name = "#Application.c_script_dropfileupload_path#main_dropfileupload.sh"
    arguments = """#name#"" ""#sharedPath#"""
    variable = "Variables.upload_progress"
    timeout = "500">
    </cfexecute>
    <tr>
    <td colspan="3" class="text">
    <cfquery name="getvalcount"
    datasource="#Application.c_dsn#"
    dbtype="ODBC"
    password="#Session.Password#"
    username="#Session.UserID#">
    SELECT pk_cpv_drop_file_upload.sf_drop_validate_and_count(replace(#name#,".csv","")) FROM dual
    </cfquery>
    <cfoutput> #getvalcount.sf_drop_validate_and_count# </cfoutput>
    </td>
    </tr>
    but I'm receiving the error from oracle telling: illegal zero-length identifier
    My question is...
    IS there a way to pass the parameter #name# to this function sf_drop_validate_and_count ? or should I work with parameters to a stored procedure?
    Thanks in advance
    Regards
    Alex

    Hi ALL,
    Just to inform you that I've found a solution when you need to apply variables as a parameter:
    preserveSingleQuotes(vFileName)
    preserveSingleQuotes function will keep the string like this 'dadsadsad' and so, you can use it inside your functions, procedures, etc..
    Thanks for all the reponses I've received.
    Best regards
    Alex

  • Oracle function to extract data into excel sheet within a script

    I have extracted data from a couple of tables onto a view. Basically I have got about 15 coloums in that view but i need to extract the data in the view into an Excel sheet.
    I just want to know if their is a function in oracle whereby i can export the data in the view onto an excel sheet, because this statements is going to be scripted and run every morning for the data to be processed.
    Oracle version: oracle 9i
    OS : Windows 2003

    If this is a one-off then IDEs such as TOAD typically
    let you export the results of a query in an
    appropriate format for Excel.Note:
    because this statements is going to be scripted and run
    every morning for the data to be processedSo that won't be feasible in this case, but it was a good point to make.

  • Oracle 7.3.4 select into using long datatype

    How do I copy values using plain SQL
    Scenario
    Table T1 (C1 int, C2 long)
    Table T2 (C1 int, C2 long)
    T1 has the following value in the respective columns
    C1 = 1
    C2 = ('A','B')
    Now I tried the following
    Insert into T1 select * from T2 ;
    This is Illegal
    How do I workaround and Is there a workaround ??
    Thanks in Advance
    null

    Hi Gopal,
    The earliest version (if Client & Server) Oracle supported on Windows 2000 was 8.1.6, now de-supported.
    Currently certified are 8.1.7 and 9.0.1.
    7.3.4 is long out of support, and there have been some fairly radical changes to Oracle and the Oracle network products since then, so I'd not be surprised it doesn't work.
    Bob

  • How to reduce functions with simple select query?

    I have a function to identify the root parent of a particular id. I use this in function in select query,which invokes function for every row in table.I need to merge the function inside the query itself.Please suggest  me.
    Function
    CREATE OR REPLACE FUNCTION fnroot(v_id int ) return int as
    v_left int;
    v_right int;
    v-result int;
    begin
    select left,right into v_left,v_right from sam where id=v_id;
    select id into v_result from sam
    where id in (select id from mst m where m.depth=2 )
    and left < v_left and right > v_right;
    return v_result;
    end
    query:
    select fnroot(s.id) from master s;

    Hi,
    Ramin's idea is very good. You must use joins in function as below
    CREATE OR REPLACE FUNCTION fnroot(v_id int ) return int as
        v_result int;
    Begin
    select  s.id into v_result
      from sam s on s.id = v_id
               left join sam s2 on (s2.id in (select id from mst m where m.depth = 2) and s2.left < s.left and s2.right > s.right)
    return v_result;
    End;
    Regards
    Mahir M. Quluzade

Maybe you are looking for

  • FCC Content conversion problem

    Hi Experts, i have a problem with with converting my file structure . My structure is Record Rec_header PO_DATA REC-RATA Header_Data Debit_Memo1 Trailer In my test file PO-DATA as well as REC_DATA are coming. I m using fieldFixedLengths In PO_DATA we

  • How to reflash my n97 mini?

    I bought an unlocked n97 mini but stupid me bought it from optus as telstra was sold out. So i can make calls etc just fine but I can't seem to use the internet/maps etc as it's trying to go through Optus Zoo. How do i reflash/set the phone so it'll

  • IMessage on ipad2 won't deliver messages!

    I've tried EVERTHING but still get "not delivered" message every time I try to send message via iMessage on iPad. Help please

  • How can I change my iTunes home library for my iPhone?

    I initially synced my iPhone with my desktop computer's iTunes, and thus that becomes its "home library", and it won't let me sync with any other computer (which is understandable). However, what if I want to change the "home library"? Like if I buy

  • Redirect based on State?

    Is there was to redirect a user to a different page based on a given State? I thought you could do it by Country using a server variable, but need to do this my a particular State. Maybe a script? This would be for a PHP site.