Constructing dynamic SQL

Forms6000. In a when_button trigger, I've coded dynamic sql statements via the concatenation method, nested within IF statements using forms_DLL built-in. Through debugging methods have confirmed that the statements are in fact being dynamically constructed or appended. Receiving form_sucess at run time but no DML is being executed against the database after concat. It's basically a simple insert statement.
Any thoughts?
Thanks..

<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Bob Muller ():
Oracle recommends against doing this because it upsets the delicate balance of the internal form (gives it gas, in other words). If you want to commit, you should use the Forms built-in to commit:
Commit_Form;
Forms commits when the user issues a kepress that results in Commit_Form (such as the Save button) or when a trigger executes Commit_Form. You might benefit from looking at the online help topic "Post and commit transactions" which has a flowchart for everything that happens here. If you use Forms_DDL to commit, you are short-circuiting the process and anything can happen.
Could the problem here be that you are looking at the database before the forms commit happens and hence not seeing the update yet?
Another alternative might be to use the DBMS_SQL package instead of Forms_DDL, look at the online help.
Yet another alternative: if you can use host variables rather than creating the insert statement, you can just put the insert statement directly into your PL/SQL code, since PL/SQL can execute INSERT directly; it cannot execute DDL (CREATE TABLE, GRANT, and so on). INSERT, UPDATE, and DELETE are not DDL statements, they are DML statements, and that's why there is no implied commit. <HR></BLOCKQUOTE>
Thanks for the response Bob,
I'm researching the help files for review of post/commit and DBMS_SQL;
Unfortunately I'm working against a database design that requires forms to view db column values as COLUMNS themselves,and as such requires a kind of re-design on-the-fly type of approach to be executed in the database at run-time pending user entries just before forms selects it's data through an relative view at runtime.
Up and runnning, but was made more difficult by inability construct sql filters 'via user entry'. May need to re-engineer upon performance evaluation.
So. really appreciate the help.

Similar Messages

  • Dynamic SQL in BPEL

    Hi All,
    Is it possible to construct dynamic SQl query in BPEL/ in DBadapter..?
    My usecase is
    1)BPEL receives input
    2) Input contains <document-id> tags at various parts of input XML, each time no of <document-id> tags may vary
    3) I want to include <document-id> tag values in Query construction, but I dont know how many times <document-id> reapeats in the Input..
    How to do this case...?
    Any suggestions..?
    Thanks

    answered in:
    Bind variables in SQL query of DBAdapter

  • 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

  • Can we use Dynamic SQL in Oracle Reports ?

    Hi ,
    Can we use Dynamic SQL in Oracle Reports ?
    If yes please give some examples .
    Thanx
    srini

    I believe the built-in package SRW.Do_Sql is what you are looking for
    Example from the document:
    /* Suppose you want to create a "table of contents" by getting the
    ** first character of a columns value, and page number on which its
    ** field fires to print. Assume that you want to put the "table of
    contents"
    ** into a table named SHIP. You could write the following construct:
    DECLARE
    PAGE_NO NUMBER;
    PAGE_FOR INDEX NUMBER;
    SORT_CHAR CHAR(1);
    CMD_LINE CHAR(200);
    BEGIN
    SORT_CHAR := :SORT_NAME ;
    IF :CALLED = Y THEN
         SRW.GET_PAGE_NUM(PAGE_FOR_INDEX);
         SRW.USER_EXIT(RWECOP PAGE_FOR_INDEX
         P_START_PAGENO);
         SRW.MESSAGE(2,TO_CHAR(:P_START_PAGENO));
    END IF;
    SRW.GET_PAGE_NUM(PAGE_NO);
    CMD_LINE := INSERT INTO SHIP VALUES
                          (||SORT_CHAR||,||TO_CHAR(PAGE_NO)||);
    SRW.MESSAGE(2,CMD_LINE);
    SRW.DO_SQL(CMD_LINE);
    COMMIT;
    EXCEPTION
      WHEN DUP_VAL_ON_INDEX THEN
            NULL;
      WHEN SRW.DO_SQL_FAILURE THEN
            SRW.MESSAGE(1,FAILED TO INSERT ROW INTO SHIP TABLE);
      WHEN OTHERS THEN
           COMMIT;
    END;

  • ORA-01008 with ref cursor and dynamic sql

    When I run the follwing procedure:
    variable x refcursor
    set autoprint on
    begin
      Crosstab.pivot(p_max_cols => 4,
       p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by job order by deptno) rn from scott.emp group by job, deptno',
       p_anchor => Crosstab.array('JOB'),
       p_pivot  => Crosstab.array('DEPTNO', 'CNT'),
       p_cursor => :x );
    end;I get the following error:
    ^----------------
    Statement Ignored
    set autoprint on
    begin
    adsmgr.Crosstab.pivot(p_max_cols => 4,
    p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by
    p_anchor => adsmgr.Crosstab.array('JOB'),
    p_pivot => adsmgr.Crosstab.array('DEPTNO', 'CNT'),
    p_cursor => :x );
    end;
    ORA-01008: not all variables bound
    I am running this on a stored procedure as follows:
    create or replace package Crosstab
    as
        type refcursor is ref cursor;
        type array is table of varchar2(30);
        procedure pivot( p_max_cols       in number   default null,
                         p_max_cols_query in varchar2 default null,
                         p_query          in varchar2,
                         p_anchor         in array,
                         p_pivot          in array,
                         p_cursor in out refcursor );
    end;
    create or replace package body Crosstab
    as
    procedure pivot( p_max_cols          in number   default null,
                     p_max_cols_query in varchar2 default null,
                     p_query          in varchar2,
                     p_anchor         in array,
                     p_pivot          in array,
                     p_cursor in out refcursor )
    as
        l_max_cols number;
        l_query    long;
        l_cnames   array;
    begin
        -- figure out the number of columns we must support
        -- we either KNOW this or we have a query that can tell us
        if ( p_max_cols is not null )
        then
            l_max_cols := p_max_cols;
        elsif ( p_max_cols_query is not null )
        then
            execute immediate p_max_cols_query into l_max_cols;
        else
            RAISE_APPLICATION_ERROR(-20001, 'Cannot figure out max cols');
        end if;
        -- Now, construct the query that can answer the question for us...
        -- start with the C1, C2, ... CX columns:
        l_query := 'select ';
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        -- Now add in the C{x+1}... CN columns to be pivoted:
        -- the format is "max(decode(rn,1,C{X+1},null)) cx+1_1"
        for i in 1 .. l_max_cols
        loop
            for j in 1 .. p_pivot.count
            loop
                l_query := l_query ||
                    'max(decode(rn,'||i||','||
                               p_pivot(j)||',null)) ' ||
                                p_pivot(j) || '_' || i || ',';
            end loop;
        end loop;
        -- Now just add in the original query
        l_query := rtrim(l_query,',')||' from ( '||p_query||') group by ';
        -- and then the group by columns...
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        l_query := rtrim(l_query,',');
        -- and return it
        execute immediate 'alter session set cursor_sharing=force';
        open p_cursor for l_query;
        execute immediate 'alter session set cursor_sharing=exact';
    end;
    end;
    /I can see from the error message that it is ignoring the x declaration, I assume it is because it does not recognise the type refcursor from the procedure.
    How do I get it to recognise this?
    Thank you in advance

    Thank you for your help
    This is the version of Oracle I am running, so this may have something to do with that.
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.8.0 - Production
    I found this on Ask Tom (http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3027089372477)
    Hello, Tom.
    I have one bind variable in a dynamic SQL expression.
    When I open cursor for this sql, it gets me to ora-01008.
    Please consider:
    Connected to:
    Oracle8i Enterprise Edition Release 8.1.7.4.1 - Production
    JServer Release 8.1.7.4.1 - Production
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1;
      8  end;
      9  /
    declare
    ERROR at line 1:
    ORA-01008: not all variables bound
    ORA-06512: at line 5
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1, 2;
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    And if I run the same thing on 10g -- all goes conversely. The first part runs ok, and the second
    part reports "ORA-01006: bind variable does not exist" (as it should be, I think). Remember, there
    is ONE bind variable in sql, not two. Is it a bug in 8i?
    What should we do to avoid this error running the same plsql program code on different Oracle
    versions?
    P.S. Thank you for your invaluable work on this site.
    Followup   June 9, 2005 - 6pm US/Eastern:
    what is the purpose of this query really?
    but it would appear to be a bug in 8i (since it should need but one).  You will have to work that
    via support. I changed the type to tarray to see if the reserved word was causing a problem.
    variable v_refcursor refcursor;
    set autoprint on;
    begin 
         crosstab.pivot (p_max_cols => 4,
                 p_query => 
                   'SELECT job, COUNT (*) cnt, deptno, ' || 
                   '       ROW_NUMBER () OVER ( ' || 
                   '          PARTITION BY job ' || 
                   '          ORDER BY deptno) rn ' || 
                   'FROM   emp ' ||
                   'GROUP BY job, deptno',
                   p_anchor => crosstab.tarray ('JOB'),
                   p_pivot => crosstab.tarray ('DEPTNO', 'CNT'),
                   p_cursor => :v_refcursor);
    end;
    /Was going to use this package as a stored procedure in forms but I not sure it's going to work now.

  • Ref cursors and dynamic sql..

    I want to be able to use a fuction that will dynamically create a SQL statement and then open a cursor based on that SQL statement and return a ref to that cursor. To achieve that, I am trying to build the sql statement in a varchar2 variable and using that variable to open the ref cursor as in,
    open l_stmt for refcurType;
    where refcurType is a strong ref cursor. I am unable to do so because I get an error indication that I can not use strong ref cursor type. But, if I can not use a strong ref cursor, I will not be able to use it to build the report based on the ref cursor because Reports 9i requires strong ref cursors to be used. Does that mean I can not use dynamic sql with Reports 9i ref cursors? Else, how I can do that? Any documentation available?

    Philipp,
    Thank you for your reply. My requirement is that, sometimes I need to construct a whole query based on some input, and sometimes not. But the output record set would be same and the layout would be more or less same. I thought ref cursor would be ideal. Ofcourse, I could do this without dynamic SQL by writing the SQL multiple times if needed. But, I think dynamic SQL is a proper candidate for this case. Your suggestion to use lexical variable is indeed a good alternative. In effect, if needed, I could generate an entire SQL statement and place in some place holder (like &stmt) and use it as a static SQL query in my data model. In that case, why would one ever need ref cursor in reports? Is one more efficient over the other? My guess is, in the lexical variable case, part of the processing (like parsing) is done on the app server while in a function based ref cursor, the entire process takes place in the DB server and there is probably a better chance for re-use(?)
    Thanks,
    Murali.

  • Dynamic SQL using DBMS_SQL Package

    Hi,
    How do i construct a
    "select * from :table_name(input parameter)"
    in a store proc in Oracle8 ?
    I know this is only possible using DBMS_SQL package in Oracle 8.
    I know that this is easily done using native Dyanamic SQL 8i onwards.
    Also I want to return the resultset obtained above through a REF cursor.
    Please Help !!!
    Will be greatly indebted to anyone who can supply the code or direct me to some helpful information on the net.
    Thanks in advance.
    Peeyush

    You are asking for two things here, use the tablename dynamically
    as bind variable to fetch the resultset and send the resultset to
    a stored procedure.
    I thought of doing both of them with REF Cursors, no Dynamic SQL here.
    Consider the following test,SQL> create or replace package ref_types as
      2       type r_cursor(pSal NUMBER) is ref cursor;
      3  end;
      4  /
    Package created.
    -- Please note that I did some quick and dirty coding to switch
    -- between the table names to show the results.
    SQL> create or replace procedure p_dynamic_table
      2  (pRefCur IN ref_types.r_cursor, pTable varchar2) as
      3     emp_rec my_emp%ROWTYPE;
      4     inv_rec test444%ROWTYPE;
      5  begin
      6    loop
      7       IF UPPER(pTable) = 'MY_EMP' Then
      8          fetch pRefcur into emp_rec;
      9       Elsif UPPER(pTable) = 'INV' THEN
    10          fetch pRefCur into inv_rec;
    11       Else
    12          exit;
    13       End if;
    14       exit when pRefcur%NOTFOUND;
    15       If UPPER(pTable) = 'MY_EMP' Then
    16          dbms_output.put_line(emp_rec.empno);
    17       Elsif UPPER(pTable) = 'INV' Then
    18          dbms_output.put_line(inv_rec.seq);
    19       Else
    20         Null;
    21       End if;
    22    end loop;
    23  end;
    24  /
    Procedure created.
    SQL> declare
      2     vRefCur         ref_types.r_cursor;
      3     vTableName      Varchar2(30);
      4  begin
      5    vTableName := 'my_emp';
      6    open vRefCur for 'select * from ' || vTableName;
      7    p_dynamic_table(vRefCur, vTableName);
      8    close vRefCur;
      9    vTableName := 'inv';
    10    open vRefCur for 'select * from ' || vTableName;
    11    p_dynamic_table(vRefCur, vTableName);
    12    close vRefCur;
    13  end;
    14  /
    7369
    7499
    7521
    7566
    7654
    7698
    7782
    7788
    7839
    7844
    7876
    7900
    7902
    7934
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    PL/SQL procedure successfully completed.Thx,
    Sri

  • How to control the maximum time that a dynamic sql can execute

    Hi,
    I want to restrict the maximum time that a dynamic sql can execute in a plsql block.
    If the execution is not completed, the execution should be terminated and a exception should be raised.
    Please let me know, if there is any provision for the same in Oracle 10g.
    I was reading about Oracle Resource Database Resource Manager, which talks about restricting the maximum time of execution for Oracle session for a user.
    However I am not sure, if this can be used to control the execution of dynamic sql in a plsql block.
    Please provide some pointers.
    Thank you,
    Warm Regards,
    Navin Srivastava

    navsriva wrote:
    We are building a messaging framework, which is used to send time sensitive messages to boundary system.I assume this means across application/database/server boundaries? Or is the message processing fully localised in the Oracle database instance?
    Every message has a time to live. if the processing of message does not occurs within the specified time, we have to rollback this processing and mark the message in error state.This is a problematic requirement.. Time is not consistent ito data processing on any platform (except real-time ones). For example, messageFoo1 has a TTL (time to live) of 1 sec. It needs to read a number of rows from a table. The mere factor of whether those rows are cached in the database buffer cache, or still residing on disk, will play a major role in execution time. Physical I/O is significantly slower that logical I/O.
    As a result, with the rows on disk, messageFoo1 exceeds the 1s TTL and fails. messageFoo2 is an identical message. It now finds most of the rows that were read by messageFoo1 in the buffer cache, enabling it to complete its processing under 1s.
    What is the business logic behind the fact that given this approach, messageFoo1 failed, and the identical messageFoo2 succeeded? The only difference was physical versus logical I/O. How can that influence the business validation/requirement model?
    If it does, then you need to look instead at a real-time operating system and server platform. Not Windows/Linux/Unix/etc. Not Oracle/SQL-Server/DB2/etc.
    TTL is also not time based in other s/w layers and processing. Take for example the traceroute and ping commands for the Internet Protocol (IP) stack. These commands send an ICMP (Internet Control Message Protocol) packet.
    This packet is constructed with a TTL value too. When TTL is exceeded, the packet expires and the sender receives a notification packet to that regard.
    However, this TTL is not time based, but "+hop+" based. Each server's IP stack that receives an ICMP packet as it is routed through the network, subtracts 1 from the TTL and the forwards the packet (with the new TTL value). When a server's IP stack sees that TTL is zero, it does not forward the packet (with a -1 TTL), but instead responds back to the sender with an ICMP packet informing the sender that the packet's TTL has expired.
    As you can see, this is a very sensible and practical implementation of TTL. Imagine now that this is time based.. and the complexities that will be involved for the IP stack s/w to deal with it in that format.
    Making exact response/execution times part of the actual functional business requirements need to be carefully considered.. as this is very unusual and typically only found in solutions implemented in real-time systems.

  • Constructing Dynamic Where clause:

    Hi experts ,
    In my real time environment in java code for a select query they they are appending dynamically to where clause and retrieving the data using hybernet .I want to do this in PL/SQ
    1)is it possible ?
    2)How can i do this one
    3)Can you provide the sample document or example for this one .Please help me

    980560 wrote:
    Hi experts ,
    In my real time environment in java code for a select query they they are appending dynamically to where clause and retrieving the data using hybernet .I want to do this in PL/SQ
    1)is it possible ?Yes it is. But it is a HORRIBLE idea and explains, in part, why Hibernate is a piece of smelly +<insert derogatory term here>+ when it comes to performance, and scalability.
    Dynamic SQL is very seldom a good idea. ANY reporting environment deals with IDENTIFIABLE questions that are asked and need to be answered. A so-called ad-hoc reporting environment where any query (no matter how idiotic and illogical) can be constructed is a FAILURE on the part of the business analyst and end-user to establish actual business requirements that need to be met. (and yes, there are a lot of these failures out there that know nothing about what analysing and determining business requirements are about, despite their job titles)
    2)How can i do this one Using DBMS_SQL. Not that difficult programming wise. This in essence is what Apex uses for running web applications that provides report SQLs to execute and contents to be rendered.
    If this SQL query is constructed on behalf of a client, then you need Oracle 11g - as the DBMS_SQL cursor variable that refers to the SQL cursor created, needs to be changed into a pointer (ref cursor) in order to be passed to the client.
    3)Can you provide the sample document or example for this one.See Oracle® Database PL/SQL Packages and Types Reference guide for details and basic examples.

  • Proxy to JDBC scenario need dynamic sql query for sender .

    Hi Experts,
    I am developing proxy to jdbc scenario. in this i need to pass dynamic sql query  whre we are passing classical method like below.
    while we are passing select stmt in constant and mapped with access field  and key field mapped with key field.
    MY requirement is like instead of passing select stmt in constant where i can generate dynamically and passed in one field and mapped with access field.

    Hi Ravinder,
    A simple UDF or use of graphical mapping functions in most cases should provide you everything you need to construct a dynamic SQL statement for your requirement.
    Regards,
    Ryan Crosby

  • Query with Dynamic SQL

    Hello,
    I would like to create a Dynamic SQL in which change is the name of the table according to the outcome of the first SQL. This is possible?
    'WITH TABLE_X AS(SELECT LEVEL LVL FROM DUAL CONNECT BY LEVEL <= 12)' ||
    'SELECT A.COL1, A.COL2, B.COL1, B.COL7'                              ||
    '  FROM TABLE_A' || TABLE_X.LVL || ' A'                              ||
    '     , TABLE_B' || TABLE_X.LVL || ' B'                              ||
    ' WHERE A.COL1 = B.COL1 AND ...    'tables in database
    TABLE_A1
    TABLE_A2
    TABLE_A12
    TABLE_B1
    TABLE_B2
    TABLE_B12let me know how I can do this
    Regards

    Hi,
    Sorry, I don't see what you're trying to do.
    "Dynamic SQL" is really a mis-nomer. The number of tables and columns in a query, and their names, must be spelled out when the statement is compiled. There is nothing dynamic about it.
    In dynamic SQL, a PL/SQL procedure or another query writes all or part of query just milliseconds before it is compiled, typically using data taken from tables or supplied by a user right then.
    For example, consider this static query:
    SELECT     a.col1, a.col2, b.col1, b.col7
    FROM     table_1     a
    ,     table_2 b
    WHERE     a.col1 = b.col1;Now, say the 1 in "table_1" and the 2 in "table_2" are variables, x and y, that you will want to look up from another table every time you run this query. You can make it dynamic like this:
    sql_txt := 'SELECT  a.col1, a.col2, b.col1, b.col7 '
         || 'FROM    table_' || TO_CHAR (x) || ' a '
         || ',       table_' || TO_CHAR (y) || ' b '
         || 'WHERE   a.col_1 = b.col1';Now let's make it really interesting. Say that instead of 2 tables, and 1 join condition, you''ll have n tables and n-1 join conditions, where n has to be computed at (actually a split second before) run-time. That is, if n=4, you might need to construct a static query with 4 tables and 3 join conditions, like this:
    SELECT     a.col1, a.col2, b.col1, b.col7
    FROM     table_1     a
    ,     table_2 b
    ,     table_12 c
    ,     table_2 d
    WHERE     a.col1 = b.col1
    AND     a.col1 = c.col1
    AND     a.col1 = d.col1;You can do that using dynamic SQL, too.
    Post an example of the static query you need to build, and describe what parts of it are dynamic, and how you get the values for those parts, and someone will help you write the dynamic SQL.

  • 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

  • NVARCHAR (MAX) TO PRINT DYNAMIC SQL QUERY TO A SQL FILE

    Hi 
    I have a requirement where i need to write an SP which would construct a huge query using dynamic SQL and save the Dynamic query to a file. 
    The Dynamic SQL Variable I am using as @NVARCHAR(MAX) but since the query being built is large (>4000 characters), I am not able to select it into a table. PRINT @SQL prints the whole query but SELECT @SQL prints only upto 4000 characterrs. 
    And I need to save this huge dynamix sql to a file using the SP.
    Any thoughts as to how i can achieve this?
    Rajiv

    This is a know problem with dynamic SQL nvarchar(max) concatenation.
    See below for correct assembly of large SQL strings:
    CREATE table #temp(qry nvarchar(max));
    declare @cmd nvarchar(max);
    SELECT @cmd=CONCAT(CONVERT(nvarchar(max),N'SELECT '),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),N'FROM SYS.TABLES'));
    insert into #temp SELECT @cmd;
    select * from #temp;
    select len(qry), datalength(qry) from #temp;
    -- 16022 32044
    drop table #temp;
    Dynamic SQL:  http://www.sqlusa.com/bestpractices/dynamicsql/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • NULL and dynamic SQL

    If table testrh2 has the following columns and data
    col1 --> NULL
    col2 --> 2
    and table testrh has the following columsn and data
    col1 --> NULL
    How could I write a dynamic SQL statement to join on the nulls? I've written the following block as a starting point.
    declare
    cursor c1 is select col1 from isis.testrh;
    lval varchar2(1000);
    lval2 varchar2(1000);
    begin
    for r1 in c1 loop
    lval := 'select col2 from isis.testrh2 where col1 = '||r1.col1;
    execute immediate lval into lval2;
    dbms_output.put_line(lval2);
    end loop;
    end;

    You can't compare null values with '=' in Oracle SQL.
    Null can only be compared with <column> is null .
    You can see it when you try these two queries:
    select * from dual where null is null;  -- you will see one row
    select * from dual where null=null;  -- you will see no rowsThat's why you have to write something like
    (<column1>=<column1>   or   (<column1> is null and <column2> is null))This should also work with null:
    decode(<column1>,<column2>,1,0)=1By the way, why do you use dynamic sql?
    lval := 'select col2 from isis.testrh2 where col1 = '||r1.col1;
    I think you could replace your two lines ( lval:= ... AND execute immediate) by this:
    begin
      select col2
      into lval
      from isis.testrh2
      where decode(col1,r1.col1,1,0)=1;
      dbms_output.put_line('lval='||lval);
    exception
    when no_data_found then
      dbms_output.put_line('no data found'); -- or whatever you want
    end;Edited by: hartmutm on 02.10.2010 23:54

  • Unique id in dynamic sql

    hi all,
    I am using oracle 10g version.
    I have one table but i do not have any unique id to identify the row.
    I want to have a unique id temporarily in my select statement (dynamic sql) in a stored procedure while fetching the results, so that i can return my results along with the unique id through the cursor.
    Please help me...
    Thanks in advance to all...

    it depends if you have a more than one column that you can uniquely identify and put them together by concatenating you can have a unique id. or a rowid might help you to temporarily identify a row.
    SQL> select e.* from employee e;
    FNAME           MINIT LNAME           SSN       BDATE       ADDRESS                        SEX       SALARY SUPERSSN         DNO
    John            B     Smith           123456789 09-Jan-1965 731 fONDREN, hOUSTON, TX       M       30000.00 333445555          5
    Frankin         T     Wong            333445555 08-Dec-1955 683 Voss, Houston,Tx           M       40000.00 888665555          5
    Alicia          J     Zelaya          999887777 19-Jul-1968 3321Castle, Spring, TX         F       25000.00 987654321          4
    Jennifer        S     Wallace         987654321 20-Jun-2041 291 Berry, Bellaire, TX        F       43000.00 888665555          4
    Ramesh          K     Narayan         666884444 15-Sep-1962 975 Fire Oak, Humble, TX       F       38000.00 333445555          5
    Joyce           A     English         453453453 31-Jul-1972 5631 Rice,Houston,TX           F       25000.00 333445555          5
    Ahmad           V     Jabbar          987987987 29-Mar-1969 980 Dallas,Houston, TX         M       25000.00 987654321          4
    James           E     Borg            888665555 10-Nov-2037 450 Stone, Houston, TX         M       55000.00                    1
    8 rows selected
    SQL> select rowid, e.* from employee e;
    ROWID              FNAME           MINIT LNAME           SSN       BDATE       ADDRESS                        SEX       SALARY SUPERSSN         DNO
    AAD8pbAAJAAAJ4fAAA John            B     Smith           123456789 09-Jan-1965 731 fONDREN, hOUSTON, TX       M       30000.00 333445555          5
    AAD8pbAAJAAAJ4fAAB Frankin         T     Wong            333445555 08-Dec-1955 683 Voss, Houston,Tx           M       40000.00 888665555          5
    AAD8pbAAJAAAJ4fAAC Alicia          J     Zelaya          999887777 19-Jul-1968 3321Castle, Spring, TX         F       25000.00 987654321          4
    AAD8pbAAJAAAJ4fAAD Jennifer        S     Wallace         987654321 20-Jun-2041 291 Berry, Bellaire, TX        F       43000.00 888665555          4
    AAD8pbAAJAAAJ4fAAE Ramesh          K     Narayan         666884444 15-Sep-1962 975 Fire Oak, Humble, TX       F       38000.00 333445555          5
    AAD8pbAAJAAAJ4fAAF Joyce           A     English         453453453 31-Jul-1972 5631 Rice,Houston,TX           F       25000.00 333445555          5
    AAD8pbAAJAAAJ4fAAG Ahmad           V     Jabbar          987987987 29-Mar-1969 980 Dallas,Houston, TX         M       25000.00 987654321          4
    AAD8pbAAJAAAJ4fAAH James           E     Borg            888665555 10-Nov-2037 450 Stone, Houston, TX         M       55000.00                    1
    8 rows selected
    SQL>

Maybe you are looking for

  • How to add customized value to drop down by index binded to model attribute

    i have to Ui element Drop down by index to which i have binded model attribute for populating the values, now i want to add a customized value to it like "choose all". how can i do this ?? Thanks and regards, Aditya Deshpande

  • Special stock indicator for components

    Hi, For a configarable material a sales order is created which in turn creates a production order. Now in this production order for some materials i find that in component overview of production order indicator SP is 1 (Individual customer stock). Th

  • Nokia 225 Arabic Language Pack

    Is it possible to add the arabic language pack to the nokia 225? My mother just bought a new nokia but she loves arabic and it is necessary that she can read it on her phone. If not, could someone suggest a simple nokia (not smartphone) with the arab

  • Why do I need a snapfish account?

    why do i need a snapfish account?

  • Is it possible to re-load the apps for IPad?

    Is it possible to re-load the apps (children book, games) already paid for Ipad that my little son has deleted?