Trying to build a generic dynamic sql block

Hi,
I have this requirement of wanting to compare column values in source and target( which are almost of the same structure) based on what table name is input by the user.
I came across a sql select statement developed by Tom kyte which kind of answers the question but what i am looking for is a more generic approach so that I can dynamically build a similar query and output very similar results.
Tom's example
So, using my assumptions and making your 'test case' (it isn't a test case yet, it is lacking) a better one:
ops$tkyte%ORA10GR2> create table t1(c1 number(2) primary key, c2 varchar2(10), c3
varchar2(10));
Table created.
ops$tkyte%ORA10GR2> create table t2(c1 number(2) primary key, c2 varchar2(10), c3
varchar2(10));
Table created.
ops$tkyte%ORA10GR2>
ops$tkyte%ORA10GR2> insert into t1 values(1,'a','c');
1 row created.
ops$tkyte%ORA10GR2> insert into t2 values(1,'b','c');
1 row created.
ops$tkyte%ORA10GR2>
ops$tkyte%ORA10GR2> insert into t1 values(2,'a','b');
1 row created.
ops$tkyte%ORA10GR2> insert into t2 values(2,'a','c');
1 row created.
ops$tkyte%ORA10GR2>
ops$tkyte%ORA10GR2> insert into t1 values(3,'a','b');
1 row created.
ops$tkyte%ORA10GR2> insert into t2 values(3,'a','b');
1 row created.
ops$tkyte%ORA10GR2>
ops$tkyte%ORA10GR2> insert into t1 values(4,'a','b');
1 row created.
ops$tkyte%ORA10GR2> insert into t2 values(4,'x','y');
1 row created.
ops$tkyte%ORA10GR2>
ops$tkyte%ORA10GR2> insert into t1 values(5,'a','b');
1 row created.
ops$tkyte%ORA10GR2>
ops$tkyte%ORA10GR2> insert into t2 values(6,'a','b');
1 row created.
ops$tkyte%ORA10GR2>
ops$tkyte%ORA10GR2>
select case sum(new_cnt - old_cnt) over(partition by c1)
when 1 then 'T2 (missing in T1)'
when -1 then 'T1 (missing in T2)'
else case old_cnt when 1 then 'T1' else 'T2' end
end "TABLE"
, C1 PK, C2, C3
, case when new_cnt = 1 and count(*) over(partition by c1) > 1 then (
case when lag(c2) over(partition by c1 order by new_cnt) = c2 then 0 else 1 end
+ case when lag(c3) over(partition by c1 order by new_cnt) = c3 then 0 else 2 end
) end COL_DIF_ID
from (
select c1, c2, c3, sum(old_cnt) old_cnt, sum(new_cnt) new_cnt from (
select o.*, 1 old_cnt, 0 new_cnt from t1 o
union all
select n.*, 0 old_cnt, 1 new_cnt from t2 n
) group by c1, c2, c3 having sum(old_cnt) <> sum(new_cnt)
) order by c1, new_cnt
TABLE PK C2 C3 COL_DIF_ID
T1 1 a c
T2 1 b c 1
T1 2 a b
T2 2 a c 2
T1 4 a b
T2 4 x y 3
T1 (missing in T2) 5 a b
T2 (missing in T1) 6 a b
It beautifully does the job but can we make this more generic in any manner using dynamic sql ?

Hi,
try this:
declare
cTable1 varchar2(30):='T1';
cTable2 varchar2(30):='T2';
cPK varchar2(30):='c1';
cSQL varchar2(4000):=null;
bFirst boolean:=true;
begin
cSQL:='select t1.*,t2.*,(case when t1.'||cPK||' is null then ''Missing in T1'' else null end) exists_t1,(case when t2.'||cPK||' is null then ''Missing in T2'' else null end) exists_t2,';
for c in(select column_name from
(select column_name from  user_tab_columns where table_name=cTable1 and column_name!=cPK
intersect
select column_name from  user_tab_columns where table_name=cTable2 and column_name!=cPK)) loop
if bFirst then
cSQL:=cSQL||'(case when';
bFirst:=false;
else
cSQL:=cSQL||' and ';
end if;
cSQL:=cSQL||'(t1.'||c.column_name||'=t2.'||c.column_name||' or (t1.'||c.column_name||' is null and t2.'||c.column_name||' is null))';
end loop;
cSQL:=cSQL||' then ''='' else ''!='' end) diff_t1_t2 from '||cTable1||' t1 full outer join '||cTable2||' t2 on(t1.'||cPK||'=t2.'||cPK||')';
dbms_output.put_line(cSQL);
end;then you can enclose the generated SQL with a select * from (..) where diff_t1_t2='!='
It will give you something like:
SELECT t1.*,
       t2.*,
       (CASE
           WHEN t1.c1 IS NULL THEN 'Missing in T1'
           ELSE NULL
        END) exists_t1,
       (CASE
           WHEN t2.c1 IS NULL THEN 'Missing in T2'
           ELSE NULL
        END) exists_t2,
       (CASE
           WHEN(   t1.C1 = t2.C1
                OR (    t1.C1 IS NULL
                    AND t2.C1 IS NULL))
        AND    (   t1.C2 = t2.C2
                OR (    t1.C2 IS NULL
                    AND t2.C2 IS NULL))
        AND    (   t1.C3 = t2.C3
                OR (    t1.C3 IS NULL
                    AND t2.C3 IS NULL)) THEN '='
           ELSE '!='
        END
       ) diff_t1_t2
FROM   T1 t1 FULL OUTER JOIN T2 t2 ON(t1.c1 = t2.c1)JV
Edited by: user11268895 on Jun 16, 2010 8:25 AM
Edited by: user11268895 on Jun 16, 2010 8:27 AM
Edited by: user11268895 on Jun 16, 2010 8:29 AM

Similar Messages

  • Need generic dynamic sql query to generate nodes depending on dealer levels

    Input table:
    create table #test(dealerid integer ,dealerlvl integer)
    insert into #test values(1,1)
    insert into #test values(1,2)
    insert into #test values(1,3)
    insert into #test values(1,4)
    insert into #test values(2,1)
    insert into #test values(2,2)
    insert into #test values(2,3)
    insert into #test values(2,4)
    insert into #test values(2,5)
    insert into #test values(2,6)
    go
    create table #test2(dealerid integer,node integer,prntnode integer,dealerlvl integer)
    insert into #test2 values (1,234,124,2)
    insert into #test2 values (1,123,234,1)
    insert into #test2 values (1,238,123,2)
    insert into #test2 values (1,235,238,3)
    insert into #test2 values (1,253,235,4)
    insert into #test2 values (2,21674,124,3)
    insert into #test2 values (2,1233,21674,1)
    insert into #test2 values (2,2144,1233,2)
    insert into #test2 values (2,2354,2144,3)
    insert into #test2 values (2,24353,2354,4)
    insert into #test2 values (2,245213,24353,5)
    insert into #test2 values (2,2213,245213,6)
    Expected result :
    I have two test case here with dealerID1 and dealerID 2 
    Result for DealerID1
    Result needed for DealerID2:
    the levels for dealers might change (Dealer1 has 4 levels, and Dealer 2 has 6 levels) so i need to create an dynamic sql query which lists each node as separate columns depending on the levels. 
    I have hacked the query to give the result I need 
    select a.dealerid,a.node as Lvl1,b.node as lvl2,c.node as lvl3,d.node as lvl4
    from #test2 a 
    join #test2 b on a.node=b.prntnode
    join #test2 c on b.node=c.prntnode
    join #test2 d on c.node=d.prntnode
    where a.dealerid=1 and a.dealerlvl=2
    select  a.dealerid,a.node asLvl1,
    b.node as lvl2,c.node as lvl3,d.node as lvl4,e.node as lvl5,f.node as lvl6--,a.dealerlvl,a.dealerid
    from #test2 a 
    join #test2 b on a.node=b.prntnode
    join #test2 c on b.node=c.prntnode
    join #test2 d on c.node=d.prntnode
    join #test2 e on d.node=e.prntnode
    join #test2 f on e.node=f.prntnode
    where a.dealerid=2 and a.dealerlvl=3
    I am sure there is a better way to do this with dynamic sql. please help.
    Thanks

    -- Dynamic PIVOT
     DECLARE @T AS TABLE(y INT NOT NULL PRIMARY KEY);
    DECLARE
       @cols AS NVARCHAR(MAX),
       @y    AS INT,
       @sql  AS NVARCHAR(MAX);
    -- Construct the column list for the IN clause
     SET @cols = STUFF(
       (SELECT N',' + QUOTENAME(y) AS [text()]
        FROM (SELECT DISTINCT dealerlvl AS y FROM dbo.test2) AS Y
        ORDER BY y
        FOR XML PATH('')),
       1, 1, N'');
    -- Construct the full T-SQL statement
     -- and execute dynamically
     SET @sql = N'SELECT *
     FROM (SELECT dealerid, dealerlvl, node
           FROM dbo.Test2) AS D
       PIVOT(MAX(node) FOR dealerlvl IN(' + @cols + N')) AS P;';
    EXEC sp_executesql @sql;
     GO

  • Best way to spool DYNAMIC SQL query to file from PL/SQL

    Best way to spool DYNAMIC SQL query to file from PL/SQL [Package], not SqlPlus
    I'm looking for suggestions on how to create an output file (fixed width and comma delimited) from a SELECT that is dynamically built. Basically, I've got some tables that are used to define the SELECT and to describe the output format. For instance, one table has the SELECT while another is used to defined the column "formats" (e.g., Column Order, Justification, FormatMask, Default value, min length, ...). The user has an app that they can use to customize the output...which leaving the gathering of the data untouched. I'm trying to keep this formatting and/or default logic out of the actual query. This lead me into a problem.
    Example query :
    SELECT CONTRACT_ID,PV_ID,START_DATE
    FROM CONTRACT
    WHERE CONTRACT_ID = <<value>>Customization Table:
    CONTRACT_ID : 2,Numeric,Right
    PV_ID : 1,Numeric,Mask(0000)
    START_DATE : 3,Date,Mask(mm/dd/yyyy)The first value is the kicker (ColumnOrder) as well as the fact that the number of columns is dynamic. Technically, if I could use SqlPlus...then I could just use SPOOL. However, I'm not.
    So basically, I'm trying to build a generic routine that can take a SQL string execute the SELECT and map the output using data from another table to a file.
    Any suggestions?
    Thanks,
    Jason

    You could build the select statement within PL/SQL and open it using a cursor variable. You could write it to a file using the package 'UTL_FILE'. If you want to display the output using SQL*Plus, you could have an out parameter as a ref cursor.

  • Error in PL/SQL Block of Trigger

    Hi all,
    I have written a trigger whose PL/SQL block contains a simple select statment among many other statements.
    Now I find that, if the select statement returns no rows the trigger does not continue its operation further and aborts there itself. And if the select statement returns some rows, then it works fine.
    I tried to execute a simplified PL/SQL block of the trigger in SQL*Plus and following were the results:
    declare
    tempdate date;
    begin
    select trdt into tempdate from inv_trans;
    if sql%notfound then
    null;
    end if;
    end;
    When no data is present in inv_trans table, the result was:
    declare
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at line 4
    And when the table inv_trans had data, the result was:
    PL/SQL procedure successfully completed.
    Why is the piece of code flashing an error when I have already given a treatment if no data is found.
    Why is it taking "No Data in table" as an abnormal condition and not normal?
    THanks in advance
    Warm Regards
    Manu

    In your case you have to use a cursor:
    declare
      cursor c_cur is
        select trdt from inv_trans;
      r_cur   c_cur%rowtype;
    begin
      open c_cur;
      fetch c_cur into r_cur;
      if c_cur%notfound then
    [pre]                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Anonymous PL/SQL block within a select statement

    I read somewhere that it was possible to build an anonymous pl/sql block within a sql statement. Something along the lines of:
    select
    begin
    i = 0;
    return i;
    end;
    from dual;
    However, for the life of me, I can't find documentation on this. Could someone please point me to the right place, assuming I'm not just imagining it.
    Thanks.

    Did you mean, executing a pl/sql block generated from an sql.
    declare
    cmd varchar2(100);
    begin
    select 'declare i pls_integer := 0; begin i:=1; end;' into cmd from dual;
    execute immediate cmd;
    end;
    [pre]                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Building Field Symbols Dynamically

    Hi All,
    Has anyone tried to build field symbols dynamically? something like this...
      DATA: field_symbol(13) TYPE c,
            v_lines          TYPE sy-tabix,
            v_count(2)       TYPE n.
      FIELD-SYMBOLS: <f2> TYPE ANY.
      DESCRIBE TABLE itab LINES v_lines.
      DO v_lines TIMES.
        v_count = v_count + 1.
        CONCATENATE '<fs_new_sf' v_count '>' INTO field_symbol.
        ASSIGN (field_symbol) TO <f2>.
        CONCATENATE '<fs_new_sf' v_count '>' INTO field_symbol.
        ASSIGN (field_symbol) TO <f2>.
        ASSIGN  COMPONENT v_sf01 OF STRUCTURE s_MARA TO <f2>.
      ENDDO.
    V_SF01 could be anything from MATNR to any field in table MARA.
    Although the above code is correct syntactically, and though there is no program termination either.
    the statement
    ASSIGN (field_symbol) TO <f2>.
    fails to assign the field symbol.
    Thanks,
    S-ray

    Hi Sudheer,
    There is a program termination because does not exist a field symbol called <fs_new_sf1> or <fs_new_sf2>... <fs_new_sfn> when you assign (field_symbol) TO <f2>.
    You should look for Dymamic Type specification, something like this:
    DATA: dref TYPE REF TO DATA.
    FIELD-SYMBOLS: <dobject> TYPE any.
    PERFORM declareData USING dref 'SFLIGHT'.
    ASSIGN dref->* to <dobject>.
    FORM declareData USING dref TYPE REF TO DATA
                           tname TYPE string.
    Create a data object of type 'tname'
    CREATE DATA dref TYPE (tname).
    ENDFORM.
    regards,
    Alejandro.

  • How to rename C00n generic column names in a Dynamic SQL report

    I have a an interface whereby the user can select 1 to 60 (upper limit) columns out of 90 possible columns (using a shuttle) from one table before running a report.
    To construct the SQL that will eventually execute, I'm using a "PLSQL function body returning SQL query" with dynamic SQL. The only problem is that I have to use "Generic Column Names" option to be able to compile the code and end up with c001 to c060 as the column names.
    How can I use the names of the selected columns as the report headings rather than c001, C002... etc?
    I do not know beforehand which columns, or how many columns or the order of the selected columns.
    I know Denes K has a demo called Pick Columns but I can't access his code. I have a hunch though that he may be just using conditions to hide/show the apropriate columns.
    thanks in advance
    PaulP

    Hi Paul
    I would change the Heading Type in the Report Details screen to PLSQL and use the shuttle item to return the column values. e.g.
    RETURN :p1_shuttle;
    I'm assuming the shuttle already has a colon separated list of the column headings in the correct order?
    I hope that helps
    Shunt

  • Dynamic sql and block based on a stored procedure

    Hi!
    I'm triying to generate a block based on a stored procedure. I want the stored procedure to execute a dynamic sql, but I'm having getting the error "PLS-00455 cursor 'AULOCASLATE' cannot be used in dynamic SQL OPEN statement".
    I have the following code:
    CREATE OR REPLACE package pkg_f0015 is
    type rClieInstSlate is record
    (clie_id CMS_CLIENTS.ID%type
    ,client_nm varchar2(1000)
    ,cs_no CMS_CLIENTS.CS_NO%type
    ,dob CMS_CLIENT_NAMES.BIRTH_DT%type);
    type tClieInstSlate is table of rClieInstSlate;
    type uClieInstSlate is ref cursor return rClieInstSlate;
    procedure prLocationSlateQry(
    auLocaSlate in out uClieInstSlate,                anCsNo in CMS_CLIENTS.CS_NO%type,
    avClieNm in varchar2,
    avSearchType in varchar2,
    avLotyCd in CMS_LOCATION_TYPES.CD%type);
    end pkg_f0015;
    CREATE OR REPLACE PACKAGE BODY pkg_cms_f0015 is
    procedure PRLocationSlateQry( auLocaSlate in out uClieInstSlate,
    anCsNo in CMS_CLIENTS.CS_NO%type,
    avClieNm in varchar2,
    avSearchType in varchar2,
    avLotyCd in CMS_LOCATION_TYPES.CD%type) IS
    vSelect varchar2(5000);
    vAddCond varchar2(1000);
    vSupLevel varchar2(50);
    begin
    vSelect := 'select clie.ID,'||
    ' CLIENT_NAME,'||
    ' clie.CS_NO,'||
    ' clna.BIRTH_DT dob'
    ' from CMS_CLIENT_NAMES clna,'||
    'CMS_CLIENTS clie'||
    ' where clna.CLIE_ID = clie.ID';
    if avSearchType= 'C' then
    vAddCond := ' and clie.CS_NO = nvl('||anCsNo||',clie.CS_NO)';
    vSelect := vSelect || vAddCond;
    open auLocaSlate for vSelect;
    end if;
    end PRLocationSlateQry;
    end;
    I wonder if what I want is possible

    OK,
    Now it works. Previously we had the parameter p_guid declared as RAW, which obviously is not any good. :)
    Radovan
    Edited by: biciste on Apr 28, 2009 4:57 PM

  • Execute Dynamic SQL statement using procedure builder

    i want to execute a dynamic SQL statment using procedure builder not using forms
    because my statement depending on a variable table name
    i know that i can do that from forms using
    FORMS_DDL('SQL_STAT');
    but i wanna to use the procedure builder
    which function i should use and how?
    please explain in example if you don't mind.
    thanks

    Hi,
    You can very well use DBMS_SQL Package supplied by Oracle for doing this.
    Search for DBMS_SQL in OTN. You will get all info regarding this.
    Regards.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial, Helvetica">quote:</font><HR>Originally posted by itslul:
    i want to execute a dynamic SQL statment using procedure builder not using forms
    because my statement depending on a variable table name
    i know that i can do that from forms using
    FORMS_DDL('SQL_STAT');
    but i wanna to use the procedure builder
    which function i should use and how?
    please explain in example if you don't mind.
    thanks<HR></BLOCKQUOTE>
    null

  • Dynamic SQL in Form Builder 6.0

    Hai,
    I would like to know how to create Dynamic SQL in Form Builder 6.0. I'am using oracle 9i database...Please help me.....

    I studied the EXEC_SQL and i wrote these syntax(below), but it gives me error...Could you help me please......:
    PROCEDURE Dynamic_sql IS
    connection_id EXEC_SQL.CONNTYPE;
    cursorID EXEC_SQL.CURSTYPE;
    sql_string VARCHAR2(1000);
    v_pc varchar2 (4);
    v_pd varchar2 (30);
    v_poc varchar2(4);
    v_pvd DATE;
    v_pid DATE;
    exec_id PLS_INTEGER;
    out_file TEXT_IO.FILE_TYPE;
    linebuf varchar2(7000);
    vchFileName VARCHAR2(100);
    Vchfolder VARCHAR2(100);
    AppID      PLS_INTEGER;
    nmbAlert          varchar2(50);
    BEGIN
    SET_APPLICATION_PROPERTY(CURSOR_STYLE,'BUSY');
    vchFileName := 'dynamic_sql_'||sysdate||'.txt';
    Vchfolder := 'D:\KONS\Damar\';
    host('mkdir '||Vchfolder,NO_SCREEN);
    out_file := text_io.fopen(vchfolder||vchFileName,'w');
    TEXT_IO.PUT_LINE (out_file,'PRODUCT CODE PRODUCT DESC PRODUCT OBJECT CODE PRODUCT VALID DATE PRODUCT INVALID DATE ');
    connection_id := EXEC_SQL.OPEN_CONNECTION('FIFDBA/F1FDBA@REPL_DAILY');
    cursorID := EXEC_SQL.OPEN_CURSOR(connection_id);
    sql_string := 'SELECT PROD_CODE, PROD_DESC, PROD_OBJT_CODE, PROD_VALID_DATE, PROD_INVALID_DATE
    FROM HOUS_PRODUCT_TYPE ';
    EXEC_SQL.PARSE(connection_id, cursorID, sql_string, exec_sql.V7);
    --EXEC_SQL.BIND_VARIABLE(connection_id, cursorID, '', input_empno);
    EXEC_SQL.DEFINE_COLUMN(connection_id, cursorID, 1,v_pc, 4);
    EXEC_SQL.DEFINE_COLUMN(connection_id, cursorID, 2, v_pd, 30);
    EXEC_SQL.DEFINE_COLUMN(connection_id, cursorID, 3, v_poc, 4);
    EXEC_SQL.DEFINE_COLUMN(connection_id, cursorID, 4, v_pvd);
    EXEC_SQL.DEFINE_COLUMN(connection_id, cursorID, 5, v_pid);
    exec_id := EXEC_SQL.EXECUTE(connection_id, cursorID);
    WHILE (EXEC_SQL.FETCH_ROWS(connection_id, cursorID) > 0 ) LOOP
    EXEC_SQL.COLUMN_VALUE(connection_id, cursorID, 1, v_pc, 4);
    EXEC_SQL.COLUMN_VALUE(connection_id, cursorID, 2, v_pd);
    EXEC_SQL.COLUMN_VALUE(connection_id, cursorID, 3, v_poc);
    EXEC_SQL.COLUMN_VALUE(connection_id, cursorID, 4, v_pvd);
    EXEC_SQL.COLUMN_VALUE(connection_id, cursorID, 5, v_pid);
    TEXT_IO.PUT_LINE(out_file,v_pc || v_pd ||v_poc||v_pvd||v_pid);
    --Forms_DDL('INSERT INTO TEMP VALUES('||''''||nRows||' '||v_state_id||''''||')');
    --COMMIT_FORM();
    END LOOP;
    EXEC_SQL.CLOSE_CURSOR(connection_id, cursorID);
    EXEC_SQL.CLOSE_CONNECTION(connection_id);
    SET_APPLICATION_PROPERTY(CURSOR_STYLE,'DEFAULT');
    TEXT_IO.FCLOSE(out_FILE);

  • Dynamic PL/SQL block vs dynamic SQL SELECT

    Hi there,
    I have a question regarding the optimal way to code a dynamic SELECT INTO statement. Below are the 2 posiibilities I know of:
    _1. Dynamically executing the SELECT statement and making use of the INTO clause of the EXECUTE IMMEDIATE statement_
    CREATE OR REPLACE FUNCTION get_num_of_employees (p_loc VARCHAR2, p_job VARCHAR2)
    RETURN NUMBER
    IS
    v_query_str VARCHAR2(1000);
    v_num_of_employees NUMBER;
    BEGIN
    v_query_str := 'SELECT COUNT(*) FROM emp_'
    || p_loc
    || ' WHERE job = :bind_job';
    EXECUTE IMMEDIATE v_query_str
    INTO v_num_of_employees
    USING p_job;
    RETURN v_num_of_employees;
    END;
    _2. Encapsulating the SELECT INTO statement in a block and dynamically exectuting the block_
    CREATE OR REPLACE FUNCTION get_num_of_employees (p_loc VARCHAR2, p_job VARCHAR2)
    RETURN NUMBER
    IS
    v_query_str VARCHAR2(1000);
    v_num_of_employees NUMBER;
    BEGIN
    v_query_str := 'begin
    SELECT COUNT(*) INTO :into_bind FROM emp_'
    || p_loc
    || ' WHERE job = :bind_job;
    end;';
    EXECUTE IMMEDIATE v_query_str
    USING out v_num_of_employees, p_job;
    RETURN v_num_of_employees;
    END;
    I was just wondering which way would be preferred? I know the second method uses a bind variable for the INTO clause, but does the first one also use bind varialbes (no semi-colon)? Any differences in terms of efficiency or speed?
    Thanks alot
    Edited by: BYS2 on Oct 19, 2011 1:23 AM

    sybrand_b wrote:
    No difference in terms of performance or speed
    Both variants will wreck the primary purpose of PL/SQL: to avoid parsing.
    When I would see a 'developer' do this, I would fire him on the spot.
    Why abuse PL/SQL in such a fashion? Both statements don't require parsing, as there is nothing dynamic in them and indicate a complete lack of understanding of Oracle, or a desire to deliver completely unscalable applications, resulting in end-users desiring to lynch you, and rightly so.
    Remove the dynamic SQL or find another job.
    Sybrand Bakker
    Senior Oracle DBANot dynamic? What if p_loc and p_job were generated dynamically based on user-input? or what if there were potentially thousands of tables that p_loc could refer to? Should I make a CASE statement with a thousand cases?
    In addition, the first example was actually taken directly from the official Oracle Database Application Developer's Guide (version 10.2). http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_dynamic_sql.htm#i1006429 - look under 'Sample Single-Row Query Using Native Dynamic SQL' heading. Therefore, if you have any issues with this alleged 'improper' usage of dynamic SQL, perhaps you should go talk to Oracle directly.
    While I appreciate your response, I don't think it has occurred that you that not everyone is a 'developer'. In fact, I have only very recently (several days ago) taught myself how to use Oracle SQL, PL/SQL and XMLDB by reading several of the official Oracle language and developer's guides. It is more a passing interest to me as I am working on some medical research which may require the use of a database. I am actually in medical school at the moment but have an undergraduate degree in Electrical and Computer engineering so I am generally well-versed in programming.
    Perhaps the next time, you post your rubbish, rude and unhelpful comments, you should stop and think that people come to this forum because they need help and not because they want to be told to 'find another job'. In fact, I am quite certain that I could make you look absolutely stupid in any topic of electrical engineering or medicine.
    Please do us all a favour and stop polluting this forum with your vapid posts. While I understand that your behavior is likely a compensatory mechanism to cope with your inferiority complex, know that help IS available if you need it.
    Edited by: BYS2 on Oct 19, 2011 2:13 AM

  • Build dynamic SQL query in Database Adapter.

    Hi All,
    I have a requirement to build dynamic sql query at Database Adapter.
    My BPEL process is getting search spec as input from siebel. I need to process this searchspec in BPEL and need to build the SQL query dynamically at Database Adapter to fetch the records from DB.
    it goes like this....
    1. Sieble Search Spec: city1 OR city2 OR city3 OR city4 .....
    I need to build query as
    select * from S_ADDR_PER where city like 'city1' OR city like 'city2' OR city like 'city3' OR city like 'city4' ......
    2. Siebel Search spec: city1 AND country1 AND state1....
    I need to build query as
    Select * from S_ADDR_PER where city like 'city1' AND country like 'country1' AND state like 'state1' ....
    3. Siebel Search spec: state
    I need to build query as
    select * from S_ADDR_PER where state like '%state%';
    Is it feasible in Database Adapter? if its Yes.
    Any guidelines to achieve this?
    Thank you
    Chandra

    Hi All,
    I have a requirement to build dynamic sql query at Database Adapter.
    My BPEL process is getting search spec as input from siebel. I need to process this searchspec in BPEL and need to build the SQL query dynamically at Database Adapter to fetch the records from DB.
    it goes like this....
    1. Sieble Search Spec: city1 OR city2 OR city3 OR city4 .....
    I need to build query as
    select * from S_ADDR_PER where city like 'city1' OR city like 'city2' OR city like 'city3' OR city like 'city4' ......
    2. Siebel Search spec: city1 AND country1 AND state1....
    I need to build query as
    Select * from S_ADDR_PER where city like 'city1' AND country like 'country1' AND state like 'state1' ....
    3. Siebel Search spec: state
    I need to build query as
    select * from S_ADDR_PER where state like '%state%';
    Is it feasible in Database Adapter? if its Yes.
    Any guidelines to achieve this?
    Thank you
    Chandra

  • Build stored procedure from a dynamic SQL query

    I have the following method, that receives a string from a textbox and creates a dynamic select command. Since I am using a dataSet I cannot execute a dynamic SQL query by calling a method of a strongly-typed dataset (.xsd). I have been told that the best
    way to do this is to pass an array of values to the stored procedure.
    But I have no clue how to build the stored procedure.
    string[] allWords = txtSearch.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    string sql = "SELECT Books.ISBN, Books.Title, Books.Tag, Books.Image, Books.photoType, Publishers.Name AS publisherName FROM Books INNER JOIN Publishers ON Books.codPublisher = Publishers.codPublisher WHERE ";
    using (SqlCommand command = new SqlCommand())
    for (int i = 0; i < allWords.Length; ++i)
    if (i > 0)
    sql += "OR ";
    string paramName = "@param" + i.ToString();
    sql += string.Format("(Books.Title LIKE {0}) ", paramName);
    command.Parameters.AddWithValue(paramName, allWords[i] + "%");
    command.CommandText = sql;
    //execute the SQL query against the db...

    After hours around this, I have came with this solution.
    private SqlConnection sqlConn = new SqlConnection();
    private System.Data.DataSet dataSet = new System.Data.DataSet();
    private System.Data.DataTable dataTable;
    private System.Data.DataRow dataRow;
    private SqlCommand search(string searchParam, int searchOption)
    SqlCommand command = new SqlCommand();
    string sql;
    string[] allWords = searchParam.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    if (searchOption == 1)
    sql = "SELECT Livros.ISBN, Livros.Titulo, Livros.Tema, Livros.Resumo, Livros.Imagem, Livros.fotoTipo, Editoras.Nome AS nomeEditora FROM Livros INNER JOIN Editoras ON Livros.codEditora = Editoras.codEditora WHERE ";
    else
    sql = "SELECT Livros.ISBN, Livros.Titulo, Livros.Tema, Livros.Resumo, Livros.Imagem, Livros.fotoTipo, Editoras.Nome AS nomeEditora FROM Livros INNER JOIN livrosAutores ON Livros.ISBN = livrosAutores.ISBN INNER JOIN Autores ON livrosAutores.idAutor = Autores.idAutor INNER JOIN Editoras ON Livros.codEditora = Editoras.codEditora WHERE ";
    using (command)
    for (int i = 0; i < allWords.Length; ++i)
    if (i > 0)
    sql += "OR ";
    if (searchOption == 1)
    sql += string.Format("(Livros.Titulo LIKE '%{0}%') ", allWords[i]);
    else
    sql += string.Format("(Livros.Autor LIKE '%{0}%') ", allWords[i]);
    command.CommandText = sql;
    return command;
    protected void Bind()
    sqlConn.ConnectionString = Properties.Settings.Default.BibliotecaConnectionString;
    string connectionString = sqlConn.ConnectionString.ToString();
    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(search(searchText, searchOption).CommandText, connectionString);
    sqlDataAdapter.Fill(dataSet, "livrosTitulo");
    dataTable = dataSet.Tables["livrosTitulo"];
    dataGrid.DataContext = dataTable.DefaultView;

  • Query Build problem in Native Dynamic SQL

    I am writing a procedure to calculate the summary from the monthly salary table by dynamically building the query using ref cursor,open cursor using the bind variables and bulding the query statement.But the query is not returning any rows
    vSQL := 'select a.ad_code,a.acc_code,m.jobtype,m.estbtype,'||'sum(m.'||vabsrec.vadsn||') from gencopayroll.pay_allowaccounthead a,'||
    'gencopayroll.pay_monthly_paybill m where bill_type = :ptype and loc_id = :plocid '||
    'and processing_period = :pprocmon and a.ad_code = :padcode group by a.acc_code,'||
    'm.jobtype,m.estbtype,a.ad_code';

    I am writing a procedure to calculate the summary
    from the monthly salary table by
    1) dynamically building the query using ref cursor
    2) open cursor using the bind variables
    3) bulding the query statement.Can you show us the code that performs these steps.
    Once a cursor is opened you need to fetch the rows from it in order to get the data.
    Also, have you checked that the query runs as plain non-dynamic SQL within SQL*Plus with the same parameters, to see that it returns data?
    What is you purpose for using Dynamic SQL? If you clarify the requirement we may be able to show you how to do the same using non-dynamic SQL.

  • SQL SP works, then throws 0x80040E14 after trying to build executable

    I have test software in LabVIEW 2011 that logs results into our SQL Server database with a stored procedure.  Once I got it working consistently, I checked it into our Visual Sorce Safe.  It was working until I tried to build the software into an executable.  Upon trying to log results in the executable, I received the following -2147217900 error when trying to execute the stored procedure (the ati_sp_InsertProcedureRun stored procedure) to create the procedure run in the database:
    NI_Database_API.lvlib:Cmd Execute.vi->DBAccess.vi->AgilentQCTool.vi->ATIEOL.vi<ERR>ADO Error: 0x80040E14
    Exception occured in Microsoft OLE DB Provider for SQL Server: Syntax error or access violation in NI_Database_API.lvlib:Rec Create - Command.vi->NI_Database_API.lvlib:Cmd Execute.vi->DBAccess.vi->AgilentQCTool.vi->ATIEOL.vi
    What's really odd is that I began receiving this error in the development environment.  On multiple computers.  I have verified that the code is still the same as before; I pulled the VI from Source Safe, which predated the last time I successfully logged results.
    I don't know if attempting to run as an executable was the precipitating event.  Around the same time, I attempted to solve a problem where the test software kept referring to VIs from the 2010 Database Connectivity Toolkit by uninstalling the 2010 Database Connectivity Toolkit and letting LabVIEW update the called VIs to the 2011 versions and saving.  I've also since tried repairing and then uninstalling and reinstalling the 2011 Database Connectivity Toolkit.
    Attached is a standalone implementation of my database logging code, a little sanitized for proprietary information.  Has anyone encountered similar mysterious errors when changing from 2010 to 2011 or when building executables?  The code I'm using is the same, and IS assures me that there have been no changes to the database.
    Thank you for any help or insight,
    John
    Solved!
    Go to Solution.
    Attachments:
    DB_UT.vi ‏10 KB
    DBAccessUnitTest.vi ‏83 KB
    DBAccessUTGenericDialog.vi ‏21 KB

    Hello,
    So far I have been unable to see anything that gives me a lead as to what the problem could be.  For this I am sorry.I think both of us will have one of those face palm moments.
    I have a question and comment for you,  does the Code still work on the original computer?
    Second,  I think it would help if you compiled a version of code with the ability to highlight execution. after being installed as an executable.  Try running the executable (in highlight mode) on the other computers and see where it breaks.
    Could you also send me a version of your code in Highlight execution mode?
    As for me I downloaded your code and I was unable to get it to even run on my computer.
    Dano
    Highlight Execution debuggable executable.
    http://ae.natinst.com/public.nsf/web/searchinternal/3087d91eeadbaf3d862571d1004af192?OpenDocument

Maybe you are looking for

  • How do you use wirelless keyboard with emoji?

    Just downloaded emoji on ipad. Have a wireless keypad! how do you use it?

  • Can't enter multiple alerts in iCal

    I can no longer program multiple alerts. After entering the first one, no popup appears to enable setting a second. This feature worked a week ago. Any ideas?  Re desktop version 5.0.2 (1571)

  • Droid no longer connecting to MacB PRO

    I have Motorola Droid2 running version 2.3.3. I can no longer connect to my MacB Pro 10.5.8 to transfer pictures. The phone is discoverable. I can see the phone on the MAC and the phone can also see the MAC but the state shows "Pairing". I have tried

  • Address Book sync with Google

    I updated my system software to 10.6.4 when the upgrade was released recently and have run into a strange glitch. My Address Book had been set up to sync with Google (in Preferences>Accounts) in previous versions of the software, and it worked withou

  • Problem installing Oracle forms and report in windows 7

    I have a problem while installing Oracle forms and reports in windows 7 64 bit The error is : [as] [ERROR] [] [oracle.as.provisioning] [tid: 20] [ecid: 0000IY5_e_EApIRMyYAhMG1BuDGr00000B,0] [[ oracle.as.provisioning.exception.ASProvWorkflowException: