Calling SQL function in SQL query fails

Hi There,
I am trying to execute INSERT INTO XML_DATA (NAME, DATASIZE, DATA) VALUES (?,?,XMLType('?')) using ODBC C
SQLBindParameter APIs.
If I execute the INSERT INTO XML_DATA (NAME, DATASIZE, DATA) VALUES (?,?,XMLType('<name>milind</name>')) works fine.
Can anybody please help me out here?
Thanks,
Milind
/* blob.c
* The following C code demonstrates how to read an input file, piecewise
* (in chunks), and write it into a BLOB or LONG RAW column in the database.
* It then reads that BLOB or LONG RAW data, piecewise, from the database
* and writes it back to the OS as an output file that you specify.
* Enter the following SQL statement via SQL*Plus to create the table
* 'images_data' for use with this sample. Make sure you log into
* Oracle as a user appropriate for running this example.
* For BLOB, use the following table:
* CREATE TABLE images_data (
* name VARCHAR2(100),
* imagesize NUMBER,
* image BLOB);
* For LONG RAW, use the following table:
* CREATE TABLE images_data (
* name VARCHAR2(100),
* imagesize NUMBER,
* image LONG RAW);
* Change the connection information at the beginning of the procedure OpenOra
* to your DSN, username and password.
* To run this program, open a Command Prompt and use the following syntax:
* Syntax: <program_name> <infile_name> <outfile_name>
* Example call: C:\> blob my_photo.jpg copy_of_my_photo.jpg
#include "stdafx.h"
#include <stdio.h>
#include <io.h>
#ifndef NUTC
#include <windows.h>
#endif
#include <sql.h>
#include <sqlext.h>
#ifdef NUTC
#include <sys/types.h>
#include <sys/stat.h>
#endif
* Global variables
HENV hOdbcEnv = NULL; /* Environment handle */
HDBC hDbConn = NULL; /* Connection handle */
int sr; /* Return value */
#define BUFSIZE 32020 /* Chunksize */
* Connect routine
void OpenOra()
char szDSN[] = "XY10g2"; /* Data Source Name (DSN) */
char szUID[] = "odbc1"; /* Username */
char szAUTH[] = "pdmuser"; /* Password */
* Allocate environment handle
sr = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hOdbcEnv);
if (sr != SQL_SUCCESS)
printf ("Error allocating environment handle\n");
* Set the ODBC Version
sr = SQLSetEnvAttr(hOdbcEnv, SQL_ATTR_ODBC_VERSION,(SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER);
if (sr != SQL_SUCCESS)
printf ("Error setting ODBC version\n");
* Allocate connection handle
sr = SQLAllocHandle (SQL_HANDLE_DBC, hOdbcEnv, &hDbConn);
if (sr != SQL_SUCCESS)
printf ("Error allocating connection handle\n");
* Connect
sr = SQLConnect(hDbConn, (UCHAR *)szDSN, SQL_NTS,(UCHAR *)szUID, SQL_NTS, (UCHAR *)szAUTH, SQL_NTS);
if (sr != SQL_SUCCESS)
printf("Connection failed\n");
* Disconnect routine
void CloseOra()
* Disconnect and free connection and environment handles
sr = SQLDisconnect(hDbConn);
if (hDbConn != SQL_NULL_HANDLE)
SQLFreeHandle(SQL_HANDLE_DBC, hDbConn);
if (hOdbcEnv != SQL_NULL_HANDLE)
SQLFreeHandle(SQL_HANDLE_ENV, hOdbcEnv);
* Read INFILE into the database and read data back out and save as OUTFILE.
void readCertImage(char read_name, long filesize, char write_name)
SQLCHAR iSqlCmd[300] = "INSERT INTO XML_DATA (NAME, DATASIZE, DATA) VALUES (?,?,XMLType('?'))";
SQLCHAR iSqlCmd1[300] = "SELECT DATA FROM XML_DATA WHERE NAME = ?";
FILE ifile, ofile; /* File pointers */
time_t startTime, endTime;
time_t startTimeIO, endTimeIO;
int IOtime = 0;
unsigned char buf[BUFSIZE]; /* Buffer to hold chunk */
unsigned char buf1[BUFSIZE]; /* Buffer to hold chunk */
SQLINTEGER type[3]; /* Type of data */
SQLPOINTER pToken; /* Which column is piecewise */
HSTMT hstmt = NULL; /* Statement handle */
long i; /* Byte Counter */
long count; /* Piecewise Counter */
long rd; /* Amount to read */
* Log on
OpenOra();
ifile = fopen(read_name, "r"); /* Open the file for reading in ASCII mode */
* Allocate statement handle
sr = SQLAllocHandle(SQL_HANDLE_STMT, hDbConn, &hstmt);
if (sr != SQL_SUCCESS)
printf("Error allocating statement handle\n");
* Prepare insert statement
sr = SQLPrepare(hstmt, iSqlCmd, SQL_NTS);
if (sr != SQL_SUCCESS)
printf("Error preparing insert statement\n");
* Bind Parameters
/* Name of BLOB */
sr = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, 0, 0,read_name, strlen(read_name), &type[0]);
if (sr != SQL_SUCCESS)
printf("Error binding name variable\n");
/* Size of BLOB */
sr = SQLBindParameter(hstmt, 2, SQL_PARAM_INPUT, SQL_C_ULONG, SQL_NUMERIC, 0, 0,&filesize, 0, &type[1]);
if (sr != SQL_SUCCESS)
printf("Error binding length variable\n");
* As this will be a piecewise insert do not need to pass a buffer here.
* Instead pass the parameter number for identification purposes.
/* BLOB data */
sr = SQLBindParameter(hstmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 0, 0,(SQLPOINTER)3, 0, &type[2]);
if (sr != SQL_SUCCESS)
printf("Error binding data variable\n");
type[0] = SQL_NTS; /* Null terminated string */
type[1] = 0; /* Ignored for numbers */
type[2] = SQL_LEN_DATA_AT_EXEC(filesize); /* Data at execution time */
time( &startTime );
* Execute the insert
sr = SQLExecute(hstmt);
if (sr == SQL_NEED_DATA)
printf("\nAbout to perform piecewise insert of data\n\n");
else if (sr != SQL_SUCCESS)
printf("Error executing insert statement\n");
* Retrieve the pointer to the buffer containing the address
* of the location where the source BLOB will be sent
sr = SQLParamData(hstmt, &pToken);
if (sr != SQL_NEED_DATA)
printf("Error - no piecewise operations required\n");
* Write the data in BUFSIZE chunks
i = 0; /* Initialize bytes inserted
count = 0; /* Initialize pieces/chunks inserted */
do
count++; /* Increment chunk number */
* If remaining bytes to read is greater than BUFSIZE,
* read another BUFSIZE chunk. Otherwise, read remaining
* chunk of bytes (which will be less than BUFSIZE)
if (filesize - i >= BUFSIZE)
rd = BUFSIZE;
else
rd = (filesize - i);
printf("%5ld:%10ld - About to write %ld bytes to the database\n",count,i,rd);
* Reads one rd sized chunk of data into buffer from source file (BLOB)
time( &startTimeIO );
fread(buf, rd, 1, ifile);
time( &endTimeIO );
IOtime = IOtime + (endTimeIO - startTimeIO);
* Sends the contents of the buffer to the ODBC driver
SQLPutData(hstmt, buf, rd);
/* Recalculate total bytes sent */
if (filesize - i >= BUFSIZE)
i+= BUFSIZE;
else
i+= (filesize - i);
} while (i < filesize);
/* Check to see if all data has been sent */
sr = SQLParamData(hstmt, &pToken);
if (sr == SQL_NEED_DATA)
printf("Error - still need data\n");
printf("%5ld:%10ld - Done writing data\n",++count,i);
time( &endTime );
printf("BLOB Write completed StartTime: %d, EndTime: %d, IOTime: %d in seconds.\n", endTime, startTime, IOtime);
printf("BLOB Write completed in %d seconds.\n", (endTime - startTime) - IOtime);
fclose(ifile); /* Close the INFILE */
printf("\nData inserted into database\n\n");
* Now read the data back. Reuse the previous statement handle.
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
sr = SQLAllocHandle(SQL_HANDLE_STMT, hDbConn, &hstmt);
if (sr != SQL_SUCCESS)
printf("Error allocating statement handle\n");
* Prepare select statement, bind variable and execute
sr = SQLPrepare(hstmt, iSqlCmd1, SQL_NTS);
if (sr != SQL_SUCCESS)
printf("Error preparing select statement\n");
sr = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, 0, 0, read_name, strlen(read_name), &type[0]);
if (sr != SQL_SUCCESS)
printf("Error binding name variable\n");
time( &startTime );
sr = SQLExecute(hstmt);
if (sr != SQL_SUCCESS)
printf ("Error executing insert statement\n");
ofile = fopen(write_name, "w"); /* Open the file for writing in ASCII mode */
sr = SQLFetch(hstmt);
if (sr != SQL_SUCCESS)
printf ("Error fetching data\n");
* Read the data in BUFSIZE chunks.
i = 0; /* Initialize bytes inserted */
count = 0; /* Initialize pieces/chunks inserted */
memset(buf, NULL, BUFSIZE);
do
* Retrieve a BUFSIZE chunk of data into the buffer
sr = SQLGetData(hstmt, 1, SQL_C_CHAR, buf, BUFSIZE, &type[2]);
if (sr == SQL_ERROR)
printf("Error fetching data\n");
break;
time( &startTimeIO );
count++; /* Increment chunk number */
/* Determine if this is a full chunk or the last chunk */
if (filesize - i >= BUFSIZE)
printf("%5ld:%10ld - About to write %ld bytes to file\n",count,i,BUFSIZE);
fwrite(buf, BUFSIZE, 1, ofile); /* Write BUFSIZE chunk to file */
else
printf("%5ld:%10ld - About to write %ld bytes to file\n",count,i,filesize-i);
fwrite(buf, filesize-i, 1, ofile); /* Write remaining chunk to file */
time( &endTimeIO );
IOtime = IOtime + (endTimeIO - startTimeIO);
/* Recalculate total bytes retrieved */
if (filesize - i >= BUFSIZE)
i+= BUFSIZE;
else
i+= (filesize - i);
} while (sr == SQL_SUCCESS_WITH_INFO);
printf("%5ld:%10ld - Done writing file\n",++count,i);
time( &endTime );
printf("BLOB Read completed StartTime: %d, EndTime: %d, IOTime: %d in seconds.\n", endTime, startTime, IOtime);
printf("BLOB Read completed in %d seconds.\n", (endTime - startTime) - IOtime);
fclose(ofile); /* Close the OUTFILE */
printf("\nData written to file\n");
* Log off
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
CloseOra();
* Main routine
void main(argc, argv)
int argc; /* Number of command line arguments */
char argv[]; / Array of command line arguments */
long filesize = 0; /* Size of INFILE */
FILE ifile; / Pointer to INFILE */
#ifdef NUTC
struct stat statbuf; /* Information on a file. */
#endif
/* Check for the proper number of command line arguments entered by user */
if (argc != 3)
printf("\nCommand line syntax: <program_name> <infile_name> <outfile_name>");
printf("\n Example call: blob input.exe output.exe\n");
exit(1);
/* Open INFILE */
if( (ifile = fopen(argv[1], "rb" )) == NULL )
printf( "\nThe file '%s' could not be opened\n",argv[1]);
exit(1);
else
printf( "\nThe file '%s' was opened successfully\n",argv[1]);
#ifdef NUTC
/* Determine length of the INFILE */
if (fstat(fileno(ifile), &statbuf) == 0)
filesize = statbuf.st_size;
else
filesize = 0;
#else
filesize = filelength(fileno(ifile));
#endif
printf( "The file is %d bytes long\n",filesize);
/* Close INFILE */
fclose(ifile);
/* Insert and retrieve BLOB */
readCertImage(argv[1], filesize, argv[2]);
}

During binding, strings are generally skipped. As such, you should first try replacing XMLType('?') with XMLType(?). You don't need to specify '?' because the system knows the proper type from your SQLBindParameter call.
Also, you should try replacing:
sr = SQLBindParameter(hstmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 0, 0,(SQLPOINTER)3, 0, &type[2]);
with
sr = SQLBindParameter(hstmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_LONGVARCHAR, 0, 0,(SQLPOINTER)buf, BUFSIZE, &type[2]);

Similar Messages

  • View calling SQL query in procedure

    Hi,
    is it possible to see in SQL procedure the SQL query, which calls this procedure? I want to log that SQL when some error occurs.
    Thanks
    SASA

    I'll be interested to see if anyone has an easy solution to this. Here's a function that will get all the currently open cursors but that's not quite the solution ...
    create or replace function f
        return varchar2 is
        v_sql_text varchar2(32767);
    begin
        for rec in (
            select v$sqltext_with_newlines.sql_text
            into v_sql_text
            from v$open_cursor,
                v$sqltext_with_newlines
            where v$open_cursor.address = v$sqltext_with_newlines.address
                and v$open_cursor.hash_value = v$sqltext_with_newlines.hash_value
                and v$open_cursor.sid = (
                    select sid
                    from v$mystat
                    where rownum = 1)
                and (v$open_cursor.address, v$open_cursor.hash_value) != (
                    select sql_address,
                        sql_hash_value
                    from v$session
                    where sid = (
                        select sid
                        from v$mystat
                        where rownum = 1))
            order by v$sqltext_with_newlines.address,
                v$sqltext_with_newlines.piece
            ) loop
            v_sql_text := v_sql_text || rec.sql_text;
        end loop;
        return v_sql_text;
    end;

  • SQL Query Fails

    Hi All,
    I am working with a SQL query for my project. Here is the Input table.
    MDNam Ord TrCode Screen Tb Parm
    wor 1 0015 H20 Meter -
    wor 2 0015 H21 Appl TTD
    wor 3 0015 H22 Order -
    wor 4 0015 H23 Time -
    wor 5 - H23 Insidental -
    wor 6 - H25 Sheet -
    Out Put
    MDNam Ord TrCode Screen Tb Parm
    wor 1 0015 H20 Meter -
    wor 3 0015 H22 Order -
    wor 4 0015 H23 Time -
    wor 5 - H23 Insidental -
    wor 6 - H25 Sheet -
    Existing query,
    SELECT * FROM Table1
    WHERE MdNam = 'Wor' AND (TrCode IS NULL OR TrCode = '0015' OR TrCode = '*') ORDER BY Ord;
    I want to change this query to get the output table, I want to keep the existing conditions in the query and filter the row which has Parm as TTD
    I tried these but failed.
    SELECT * FROM Table1
    WHERE MdNam = 'Wor' AND (TrCode IS NULL OR TrCode = '0015' OR TrCode = '*') and Parm not equals 'TTD' ORDER BY Ord;
    This change dosent give any rows.
    Thanks.
    Edited by: user10651875 on Feb 10, 2009 8:25 PM
    Edited by: user10651875 on Feb 10, 2009 8:28 PM
    Edited by: user10651875 on Feb 10, 2009 8:31 PM
    Edited by: user10651875 on Feb 10, 2009 8:37 PM
    Edited by: user10651875 on Feb 10, 2009 8:37 PM

    Dont just say its not returning any row. Show us like this.
    SQL> with t
      2  as
      3  (
      4     select 'wor' mdnam, 1 ord, '0015' trcode, 'H20' screen, 'Meter' tb, '' parm from dual union all
      5     select 'wor', 2, '0015', 'H21', 'Appl', 'TTD' from dual union all
      6     select 'wor', 3, '0015', 'H22', 'Order', '' from dual union all
      7     select 'wor', 4, '0015', 'H23', 'Time', '' from dual union all
      8     select 'wor', 5, ''    , 'H23', 'Insidental', '' from dual union all
      9     select 'wor', 6, ''    , 'H25', 'Sheet', '' from dual
    10  )
    11  select *
    12    from t
    13   where MdNam = 'wor'
    14     and (trcode is null OR trcode = '0015' or trcode = '*')
    15     and nvl(Parm,' ') != 'TTD'
    16   order by Ord;
    MDN        ORD TRCO SCR TB         PAR
    wor          1 0015 H20 Meter
    wor          3 0015 H22 Order
    wor          4 0015 H23 Time
    wor          5      H23 Insidental
    wor          6      H25 SheetEdited by: Karthick_Arp on Feb 10, 2009 8:57 PM

  • Calling another function if upate statement fails

    Hi there,
    I have written an update procedure and insert procedure. Is there a way of calling another function if the update statement fails? Thanks a lot for your help.
    Chris
    procedure update_costing(in_period in DATE,
                   in_project_id IN VARCHAR2,
                   in_user_id IN VARCHAR2,
                   in_thu IN VARCHAR2,
                   in_fri IN VARCHAR2,
                   in_sat IN VARCHAR2,
                   in_sun IN VARCHAR2,
                   in_mon IN VARCHAR2,
                   in_tue IN VARCHAR2,
                   in_wed IN VARCHAR2)
         UPDATE TBL_COSTING
              SET
                   HOURS_THU = to_date (in_thu, 'HH24:MI'),
                   HOURS_FRI = to_date (in_fri, 'HH24:MI'),
                   HOURS_SAT = to_date (in_sat, 'HH24:MI'),
                   HOURS_SUN = to_date (in_sun, 'HH24:MI'),
                   HOURS_MON = to_date (in_mon, 'HH24:MI'),
                   HOURS_TUE = to_date (in_tue, 'HH24:MI'),
                   HOURS_WED = to_date (in_wed, 'HH24:MI'),
                   WHERE PERIOD = in_period
         AND PROJECT_ID = in_project_id
         AND USER_ID = in_user_id;
    EXCEPTION
    --CALLL HERE THE INSERT FUNCTION WITH SAME DATAMEMBERS
    SOMETHING LIKE THIS---
    WHEN others then
         insert_costing(in_period, in_project_id, in_user_id ,in_thu,in_fri,in_sat,in_sun,in_mon,in_tue,in_wed ,in_submit);
    COMMIT;
    END update_costing;

    begin
    UPDATE statement
    IF SQL%ROWCOUNT =0
    then
    INSERT statement|procedure
    end if;
    end;
    /Hi,
    i have a simple doubt over here, i read somewhere that cursor attributes can be used only as long as the cursor is open, then in the above case whiel doing the update operation, oracle implicitly will open an cursor and will do the operation and then will close the cursor, then how does SQL%ROWcount works???please revert...
    cheere

  • SQL Query fails with Fetch error

    We are running JDE ERP 9.0 and have a report that gets this error
    “JDB3300020 - Fetch not allowed. Prior successful Select operation required for this request.”
    I’ve been troubleshooting this problem for months, and I am no closer to the root cause and need some help. I’ve engaged Microsoft support, we collected a trace but could not find anything that pointed to the cause.
    Execution details:
    Report runs successfully after database server is rebooted. Otherwise we have to keep rerunning as many as 15 times to get a successful run. When we discovered that report would run after the server reboot, we decided
    to only restart SQL, to see if it was Query plan related but it still failed. How can we determine why the reboot is making a difference?
    Any ideas/help is welcome.

    Using Profiler to capture what JD Edwards sends to SQL Server seems like a good idea. And include the events Error:Exception and Error:UserMessage to see if that captures anything.
    I googled on the message, and I found
    http://www.jdelist.com/ubb/showflat.php?Cat=&Number=111077&page=0&view=collapsed&sb=5&o=
    where the cause was that different indexes were used for SELECT and FETCH. (Whatever that means; I was not able to grasp it.)
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Interactive format IN BATCH FILE CALLING SQL QUERY

    Hi,
    Below code i have written to get some data from file test.txt and O/P the data from database. For this i m running MS-DOS batch file which is calling test.sql and which in turn calls the file test.sql and get desired result from database. The below script works perfectly
    What i want is the more interactive format and not hard coded format esp location and name of the TEXT FILE . How i can make changes that whenever BATCH FILE is run, it ask for file name and location and then passes those information to SQL FILE which in turn fetches the results from database
    BATCH FILE : test.bat
    sqlplus sys/xxxxx as sysdba @test.sqlSQL FILE: test.sql
    SET SERVEROUTPUT ON
    DECLARE
       lc_file_handle        UTL_FILE.file_type;
       lc_file_dir           VARCHAR2 (100);
       lc_file_name          VARCHAR2 (50);
       data                VARCHAR2 (500);
       v1                    ECCSYS.hwcontainer.hwcontainerserialnumber%type;
       v2                    ECCSYS.storagedevice.devicename%type;
       s2                    ECCSYS.storagedevice.isreserved%type;
    BEGIN
       lc_file_dir := 'DATA_PUMP_DIR';
       lc_file_name := 'test.txt';
       lc_file_handle := UTL_FILE.fopen (lc_file_dir, lc_file_name, 'R');
       LOOP
          BEGIN
             UTL_FILE.get_line (lc_file_handle, data);
         v1 := SUBSTR (data,1,INSTR (data, ',', 1) - 1);
         v2 := substr(data, INSTR (data, ',', 1, 1) + 1, length(data) - INSTR (data,',', 1, 1));
           select isreserved into s2 from ECCSYS.storagedevice where devicename=v2 and storagearrayid = (select hwcontainerid from ECCSYS.hwcontainer where hwcontainerserialnumber =v1);
         DBMS_OUTPUT.PUT_LINE(v1 ||' '|| v2 ||' '|| s2);
          EXCEPTION
             WHEN NO_DATA_FOUND
             THEN
                EXIT;
          END;
       END LOOP;
    EXCEPTION
       WHEN OTHERS
       THEN
          UTL_FILE.fclose (lc_file_handle);
    END;
    EXIT;TEXT FILE : test.txt
    000190300153,170
    000190300153,171

    Hi,
    I have made some changes in the batch and sql file but problem is , still test.sql is seeking name of the file even though its passed from batch file to sql file.
    BATCH FILE : test.bat
    @echo off
    set /P id=Enter THE FILE NAME: %=%
    echo %id%
    sqlplus sys/xxxx as sysdba @test.sql %idSQL FILE : test.sql
    SET SERVEROUTPUT ON
    DECLARE
       lc_file_handle        UTL_FILE.file_type;
       lc_file_dir           VARCHAR2 (100);
       lc_file_name          VARCHAR2 (50);
       data                VARCHAR2 (500);
       v1                    ECCSYS.hwcontainer.hwcontainerserialnumber%type;
       v2                    ECCSYS.storagedevice.devicename%type;
       s2                    ECCSYS.storagedevice.isreserved%type;
    BEGIN
       lc_file_dir := 'DATA_PUMP_DIR';
       lc_file_name := '&id';
       lc_file_handle := UTL_FILE.fopen (lc_file_dir, lc_file_name, 'R');
       LOOP
          BEGIN
             UTL_FILE.get_line (lc_file_handle, data);
         v1 := SUBSTR (data,1,INSTR (data, ',', 1) - 1);
         v2 := substr(data, INSTR (data, ',', 1, 1) + 1, length(data) - INSTR (data,',', 1, 1));
           select isreserved into s2 from ECCSYS.storagedevice where devicename=v2 and storagearrayid = (select hwcontainerid from ECCSYS.hwcontainer where hwcontainerserialnumber =v1);
         DBMS_OUTPUT.PUT_LINE(v1 ||' '|| v2 ||' '|| s2);
          EXCEPTION
             WHEN NO_DATA_FOUND
             THEN
                EXIT;
          END;
       END LOOP;
    EXCEPTION
       WHEN OTHERS
       THEN
          UTL_FILE.fclose (lc_file_handle);
    END;
    EXIT;

  • Calling boolean function from tree query

    Hi all,
    I have placed a tree on my sidebar region from the following query
    select PAGE_NO id,
    PARENT_PAGE_NO pid,
    NAME name,
    'f?p=&APP_ID.:'||page_no||':&SESSION.' link,
    null a1,
    null a2
    from #OWNER#.APEX_PAGES
    WHERE page_no = :APP_PAGE_ID
    AND nvl(navigation,'N') = 'Y'
    Its running perfectly fine. Now i have my custom function "isUserAllowed(app_user, name_of_node, isParent)" which returns a boolean expression is the logged in User has access privilege on that node.
    How can i run my function inside the tree query so that node is visible only for those values in which my function returns "true"? and not on others?
    With Regards,
    Sunil Bhatia

    The "wrapper" function would actually be pretty easy - just another function to call the one returning the boolean and convert it to some other value, numeric or character. something like (untested)
    <pre>
    FUNCTION wrapper_function(P_whatever varchar2) return varchar2 IS
    v_return_value_c varchar2(5);
    BEGIN
    r_return_value_c := case boolean_function(p_whatever)
    when true then 'true'
    else 'false;
    return v_return_value_c;
    END;
    </pre>
    Using the function in the WHERE clause could look something like this (untested, but should work if done correctly)
    <pre>
    select whatever
    from your_table
    where wrapper_function(whatever) = 'true'
    </pre>

  • Get Comma separated result from SQL Query

    Hey Everyone
    I have a requirement where i need to get comma separated result of names because there is one to many relationship i.e for every protocol there are mutiple people associated to it , and i created PL/SQL function for that and everything was fine and when it is in production multiple number of cursors were opened because of the logic and leading to RAC fail over and for that we were manually clearing the cursors every weekend and i am looking to create a Materialized view for this logic but i was unable to code the logic using Connect by clause
    Result is like and i want comma separated names for every protocol
    P06065     TESTER13 TESTER13
    P02095     PATRICIA CARMELITANO
    P02095     ANNE MUIR
    P02095     ROBERT HARLOW
    P02095     JANICE ALBERT
    P02095     Jacqueline van Dalen
    P02095     GUENTER HENNIG DR.
    P05209     Olga Xenaki
    P05553     Birgit Limbach-Angele
    P05553     Anja Schulz Dr.
    P05553     CHRISTA HAGENBUCHER
    here is the function which i wrote, i need to get the same logic through SQL Statement .. thanks for your help
    cursor c_GSCR is
    select T565804.FST_NAME||' '||T565804.LAST_NAME
    from
    S_PT_POS_HST_LS T544105 /* S_PT_POS_HST_LS_Protocol_Team */ ,
    S_CONTACT T565804 /* S_CONTACT_Protocol_Team */,
    S_CL_PTCL_LS T541903 /* S_CL_PTCL_LS_Protocol */
    where ( T541903.ROW_ID = T544105.CL_PTCL_ID and
    T544105.POSTN_ID = T565804.PR_HELD_POSTN_ID and
    T544105.ROLE_CD = 'Lead Project Manager' AND
    T541903.ROW_ID = v_PTCL_ID and
    T541903.PAR_PTCL_ID is null and T544105.END_DT is null );
    BEGIN
    l_row_num := 0;
    l_role := '';
    l_role_list := '';
    v_PTCL_ID := PTCL_ID;
    OPEN C_GSCR;
    if C_GSCR%isopen THEN
    LOOP
    FETCH C_GSCR INTO l_role;
    exit when C_GSCR%notfound;
    IF l_role_list IS NULL THEN
    l_role_list:=l_role;
    ELSE
    l_role_list:=l_role_list||', '||l_role;
    END IF;
    END LOOP;
    CLOSE C_GSCR;
    end if;
    ~Srix

    Hi,
    Srix wrote:
    Thanks for the Info .. My database in 10g R 2 i started using COLLECT Function
    select T541903.PTCL_NUM ,
    CAST(COLLECT(T565804.FST_NAME||' '||T565804.LAST_NAME) AS varchar2_ntt) , 7) AS LPM_NAME
    from
    S_PT_POS_HST_LS T544105 /* S_PT_POS_HST_LS_Protocol_Team */ ,
    S_CONTACT T565804 /* S_CONTACT_Protocol_Team */,
    S_CL_PTCL_LS T541903 /* S_CL_PTCL_LS_Protocol */
    where T541903.ROW_ID = T544105.CL_PTCL_ID and
    T544105.POSTN_ID = T565804.PR_HELD_POSTN_ID and
    T544105.ROLE_CD = 'Lead Project Manager' AND
    T541903.PAR_PTCL_ID is null and T544105.END_DT is null
    GROUP BY T541903.PTCL_NUM
    The result i like ...Do you mean "The result *is* like ..."?
    Or do you mean "The result I [would] like [is] ..."?
    The code above has unblanaced parentheses. If you are getting anything other than an error message, then I don't believe you are really running what you posted.
    Whenever you have a problem, post a complete test script that people can use to recreate the problem and test their ideas.
    Please do that. Post CREATE TABLE and INSERT statements to crate the sample data, the code you used to create the carachr2_ntt type and the function, and your best attempt at a query (formatted). Simplify as much as possible. For example, do you really need 3 tables to illustrate the problem? For purposes of asking a question on this forum, can't you pretend you have just one table, with 2 columns?
    I suspect the problem has to do with the user-defined type and function, which you didn't post. I can't even see how you called the function in your query. Without the information I mentioned above, there's not much I can do to help you.

  • Returning composite datatype(record) to an SQL Query

    I have a function called get_customer_address() that takes customer id and returns the customer address as a record type.
    TYPE cust_address_type IS RECORD
    (address1 VARCHAR2(25),
    address2 VARCHAR2(25),
    city VARCHAR2(25),
    zipcode VARCHAR(10),
    STATE VARCHAR(10));
    cust_address cust_address_type;
    My function is returning cust_address.
    I want to modify below exising query and call this function from the query to get address.
    select cust_id, address1, address2, city, zipcode from customer_table;
    Instead of using address1, address2, city, zipcode if I want to the record type variable cust_id returned from the function, can I use it in my query? How do I modify the above query to call the function get_customer_address and get the same values as in the above query?

    To add to Elic's comment - PL/SQL record structures can be defined as SQL objects, as long as SQL data types are used and not non-supported PL/SQL types like boolean.
    E.g. create or replace type TCustAddress is object
    (  address1 VARCHAR2(25),
       address2 VARCHAR2(25),
       city     VARCHAR2(25),
       zipcode  VARCHAR2(10),
       state    VARCHAR2(10)
    );This provides a lot more flexibility than using PL/SQL record types. This is essentially an object class definition - and you can add constructors and methods to it.
    It works seamlessly across both SQL and PL/SQL.

  • Calling DB function for each row in a report

    I'd like to call a function inside a database package from my Oracle Report. My report is a very simple tabular listing and I'd like to pass one the row's column value as a parameter to my function call.
    Where would i have to write this block of code? How do I get the value of a particular column in the report? I need to pass the value to the function call.
    Thanks

    Depends what you want to do in this function. There are several possibilites:
    - Add a formula column to your data model.
    - Directly call the function in your query:
    select col1, col2, my_package.my_function(col1) return_value
    from my_table
    where ...The 2nd option would be my preferred one.

  • Passing table record to a function in a query

    I have a procedure which calls a function in a query which has 2 input parameters as shown below -
    select a.id, a.name, a.sal, check_xyz_func(a.id, a.sal) from employees a
    The function check_xyz_func retiurns varchar2.
    Now the requirement is that few more columns from the same table are needed as input to this function. So instead of giving all the column names,. can i pass the entire row as input to this function. Something like => check_xyz_func (a.*).
    I tried creating a type --> TYPE rec IS TABLE OF employees%ROWTYPE and passing rec to this function, but this isn't working.

    >
    And what should i pass as parameter when calling the function
    >
    I showed you what to pass. You should pass a variable that is declared as
    employee_rec employees%ROWTYPESo you would populate 'employee_rec' and pass it to the function.
    See the pipelined function code below that declares a variable of %ROWTYPE and does a fetch into it.
        l_rec  emp%rowtype;
          fetch emp_cv into l_rec;You would then pass 'l_rec' to your function.
    -- 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))

  • SQL query slow with call to function

    I have a SQL query that will return in less than a second or two with a function in-line selected in the "from" clause of the statement. As soon as I select that returned value in the SQL statement, the statement takes from anywhere from 2 to 5 minutes to return. Here is a simplified sample from the statement:
    This statement returns in a second or 2.
    select A.pk_id
    from stu_schedule A, stu_school B, stu_year C, school_year D,
    (select calc_ytd_class_abs2(Z.PK_ID,'U') ytd_unx
    from stu_schedule Z) II
    where B.pk_id = A.fk_stu_school
    and C.pk_id = B.fk_stu_year
    and D.pk_id = C.year
    and D.school_year = '2011';
    if I add this function call in, the statement runs extremely poor.
    select A.pk_id,
    II.ytd_unx
    from stu_schedule A, stu_school B, stu_year C, school_year D,
    (select calc_ytd_class_abs2(Z.PK_ID,'U') ytd_unx
    from stu_schedule Z) II
    where B.pk_id = A.fk_stu_school
    and C.pk_id = B.fk_stu_year
    and D.pk_id = C.year
    and D.school_year = '2011';
    Here is the function that is called:
    create or replace FUNCTION calc_ytd_class_abs2 (p_fk_stu_schedule in varchar2,
    p_legality in varchar2) return number IS
    l_days_absent number := 0;
    CURSOR get_class_abs IS
    select (select nvl(max(D.days_absent),'0')
    from cut_code D
    where D.pk_id = C.fk_cut_code
    and (D.legality = p_legality
    or p_legality = '%')) days_absent
    from stu_schedule_detail B, stu_class_attendance C
    where B.fk_stu_schedule = p_fk_stu_schedule
    and C.fk_stu_schedule_detail = B.pk_id;
    BEGIN
    FOR x in get_class_abs LOOP
    l_days_absent := l_days_absent + x.days_absent;
    END LOOP;
    return (l_days_absent);
    END calc_ytd_class_abs2;

    Query returns anywhere from 6000 to 32000 rows. For each of those rows a parameter is passed in to 4 different functions to get ytd totals. When I call the functions in the in-line view but do not select from them in the main SQL, the report (oh, this is Application Express 4.0 interactive reports, just an FYI) runs fast. The report comes back in a few seconds. But when I select from the in-line view to display those ytd totals, the report runs extremely slow. I know there are the articles about context switching and how mixing SQL with PL/SQL performs poorly. So I tried a pipeline table function where the function for the ytd totals populate the columns of the pipeline table and I select from the pipeline table in the SQL query in the interactive report. That seemed to perform a little worse from what I can tell.
    Thanks for any help you can offer.

  • Error while calling the function which returns SQL Query!!!

    Hi,
    I have a Function which returns SQL query. I am calling this function in my APEX report region source.
    The query is dynamic SQL and its size varies based on the dynamic "where clause" condition.
    But I am not able to execute this function.It gives me the following error in APEX region source.
    ORA-06502: PL/SQL: numeric or value error: character string buffer too small
    Even in SQL* Plus or SQL developer also same error .
    The length of my query is more than 4000. I tried changing the variable size which holds my query in the function.
    Earlier it was
    l_query varchar2(4000)
    Now I changed to
    l_query varchar2(32767).
    Still it is throwing the same error.
    Can anybody help me to resolve this.???
    Thanks
    Alaka

    Hi Varad,
    I am already using 32k of varchar2. Then also it is not working.
    It is giving the same error. I think there is something to do with buffer size.
    My query size is not more than 4200. Even if i give 32k of varchar2 also buffer is able to hold only 3997 size of the query only.
    Error is
    ORA-06502: PL/SQL: numeric or value error: character string buffer too small
    Tried CLOB also. It is not working.
    Any other solution for this.
    Thanks
    Alaka

  • What is the best way to Optimize a SQL query : call a function or do a join?

    Hi, I want to know what is the best way to optimize a SQL query, call a function inside the SELECT statement or do a simple join?

    Hi,
    If you're even considering a join, then it will probably be faster.  As Justin said, it depends on lots of factors.
    A user-defined function is only necessary when you can't figure out how to do something in pure SQL, using joins and built-in functions.
    You might choose to have a user-defined function even though you could get the same result with a join.  That is, you realize that the function is slow, but you believe that the convenience of using a function is more important than better performance in that particular case.

  • Put SQL query in a function/ call function from region

    How can I write a SQL query (like SELECT EMPNO, ENAME, JOB FROM EMP) as PL/SQL function, and then call this function from the PL/SQL Function Returning SQL Statement region?
    Thanks, Tom

    thanks jverd for your quick reply.
    I know passing in a reference to an object will do the job if I want to change the value several parameters in one function call.
    But I want to ask, is there any other ways?
    the following code works.....
    public class TestParameter {
         public static void main(String[] args) {
              Test2 t2 = new Test2();
              invokeChange(t2);
              System.out.println("x = " + t2.x + "\t y = " + t2.y);
         static void invokeChange(Test2 t2) {
              t2.x = 10;
              t2.y = 15;          
    class Test2 {     
         int x;
         int y;     
    }

Maybe you are looking for