Execution of Clob through dynamic sql

Hi,
Here in below code.I am trying to execute the CLOB dynamically.Its giving an error as
ORA-6502
Numeric or value error.
Declare
SQL3 CLOB := '';
SQLSTRING1 LONG;
SQLSTRING2 LONG;
SQLSTRING3 LONG;
Begin
SQL3 := GENUPD(RECTABLE => 'REC_TARGET_TABLE',
TGTTABLE =>'TARGET_TABLE',
AUDITTABLE => 'DATA_AUDIT_DETAILS');
SQLSTRING1 := DBMS_LOB.SUBSTR(SQL3, 8000, 1);
SQLSTRING2 := DBMS_LOB.SUBSTR(SQL3, 8000, 8001);
SQLSTRING3 := DBMS_LOB.SUBSTR(SQL3, 8000, 16001);
EXECUTE IMMEDIATE SQLSTRING1 || SQLSTRING2 || SQLSTRING3 ;
When I am doing the same in below way its giving an above error
for i in 0 .. 2 loop
SQLSTRING1 := SQLSTRING1 ||
DBMS_LOB.SUBSTR(SQL3, 8000, 8000 * i +
end loop;
EXECUTE IMMEDIATE SQLSTRING1;
end;
Is there any way to write the aboive code in optimized manner.
Any help really appreciated.
Thanks in Advance

DECLARE 
  stmt_str varchar2(200);
  cur_hdl int;
  rows_processed int;
  name varchar2(10);
  salary int;
  v_type DBMS_SQL.varchar2s;
BEGIN
  cur_hdl := dbms_sql.open_cursor;
  v_type(1) := 'SELECT 1'||chr(10);
  v_type(2) := '  FROM DUAL'||chr(10);   
  DBMS_SQL.PARSE ( c                  => cur_hdl,
                   statement          => v_type,
                   lb                 => 1,
                   ub                 => 2,
                   lfflg              => FALSE,
                   language_flag      => dbms_sql.native );
  -- describe defines
  dbms_sql.define_column(cur_hdl, 1, name, 200);   
  rows_processed := dbms_sql.execute(cur_hdl); 
  LOOP
      -- fetch a row
      IF dbms_sql.fetch_rows(cur_hdl) > 0 then
      -- fetch columns from the row
      dbms_sql.column_value(cur_hdl, 1, name);
      Dbms_Output.put_line(name);   
      ELSE
        EXIT;
      END IF;
  END LOOP;
  dbms_sql.close_cursor(cur_hdl); -- close cursor
END;

Similar Messages

  • CLOBs and Dynamic SQL method 4

    We have just added CLOBs ( select_dp->T == 112 ) to our applications. We have a application tier server that is a Pro*C program that reads and iterprets some "extended" .sql files. We this server uses dynamic sql method 4, with host arrays, etc. The docs say you cannot do a FETCH FOR <value> with CLOBs, but you can ALLOCATE and FREE the clobLocator with a FOR clause. What good is the ALLOCATE and FREE "FOR" if you can't FETCH with a FOR ?? Can you really select clobs along with typical varchars??

    Can you tell me exactly where are you going to use the Dynamic SQL method 4 ? so that i can help you in using the method.
    Thiagu.

  • How to determine column length semantics through ANSI Dynamic SQL ?

    I am looking for a way to determine the length semantics used for a column through ANSI Dynamic SQL.
    I have a database with NLS_CHARACTERSET=AL32UTF8.
    In this database I have the following table:
    T1(C1 varchar2(10 char), C2 varchar2(40 byte))
    When I describe this table in SQL*Plus, I get:
    C1 VARCHAR2(10 CHAR)
    C2 VARCHAR2(40)
    In my Pro*C program (mode=ansi), I get the select statement on input, use PREPARE method to prepare it and then use the GET DESCRIPTOR method to obtain colum information for output:
    GET DESCRIPTOR 'output_descriptor' VALUE :col_num
    :name = NAME, :type = TYPE,
    :length = LENGTH, :octet_length = OCTET_LENGTH
    For both C1 and C2 I get the following:
    :type=12
    :length=40
    :octet_length=40
    So, even if I know that my database is AL32UTF8, there doesn't seem to be a way for me to determine whether char or byte length semantics were used in C1 and C2 column definitions.
    Does anybody know how I can obtain this information through ANSI Dynamic SQL?
    Note: the use of system views such as ALL_TAB_COLUMNS is not an option, since we wish to obtain this information even for columns in a complex select statements which may involve multiple tables.
    Note: I believe OCI provides the information that we need through OCI_ATTR_DATA_SIZE (which is in bytes) and OCI_ATTR_CHAR_SIZE (which is in chars). However, switching to OCI is something we would like to avoid at this point.

    Yes, I was wondering which forum would be the best for my question. I see similar questions in various forums, Call Interface, SQL and PL/SQL and Database - General. Unfortunately there is no Pro*C or Dynamic SQL forum which would be my first choice for posting this question.
    Anyway I now posted the same question (same subject) in the Call Interface forum, so hopefully I'll get some answers there.
    Thank you for the suggestion.

  • Question on Dynamic SQL Execution

    Hi,
    Our company is currently using Oracle 7 but will move to Oracle 8i soon. I am trying to execute a dynamic SQL statement in a function and it always error-out during execution. The SQL statement is NOT doing any update to a table. Its doing a select only. The function is being called during an execution of another dynamic SQL statement in a procedure. Here are examples of the code listing for the procedure and function:
    CREATE OR REPLACE PROCEDURE TEST_PROC
    lookup_cursor      integer;
    ignore          integer;
    VARvalue          number;
    begin
    lookup_cursor := DBMS_SQL.open_cursor;
    DBMS_SQL.PARSE( lookup_cursor,
              'SELECT ' || TEST_FUNCTION || ' FROM DUAL,
              DBMS_SQL.NATIVE);
    DBMS_SQL.DEFINE_COLUMN( lookup_cursor, 1, VARvalue);
    ignore := DBMS_SQL.EXECUTE(lookup_cursor);
    loop
         IF DBMS_SQL.FETCH_ROWS(lookup_cursor) > 0 THEN
         DBMS_SQL.COLUMN_VALUE(lookup_cursor, 1, VARvalue);
         ELSE
         EXIT;
         END IF;
    END LOOP;
    DBMS_SQL.CLOSE_CURSOR(lookup_cursor);
    end TEST_PROC;
    CREATE OR REPLACE PROCEDURE TEST_FUNCTION
    lookup_cursor      integer;
    ignore          integer;
    VARvalue          number;
    VARsql_string     VARCHAR2(200);
    begin
    lookup_cursor := DBMS_SQL.open_cursor;
    VARsql_string := SOME GENERATED SQL STATEMENT;
    DBMS_SQL.PARSE( lookup_cursor,
              VARsql_string,
              DBMS_SQL.NATIVE);
    DBMS_SQL.DEFINE_COLUMN( lookup_cursor, 1, VARvalue);
    ignore := DBMS_SQL.EXECUTE(lookup_cursor);
    loop
         IF DBMS_SQL.FETCH_ROWS(lookup_cursor) > 0 THEN
         DBMS_SQL.COLUMN_VALUE(lookup_cursor, 1, VARvalue);
         ELSE
         EXIT;
         END IF;
    END LOOP;
    RETURN VARvalue;
    end TEST_FUNCTION;
    The error I received during execution of TEST_PROC is:
    ORA-06571: Function TEST_FUNCTION does not guarantee not to update database
    ORA-06512: at "SYS.DBMS_SYS_SQL", line 239
    ORA-06512: at "SYS.DBMS_SQL", line 32
    It may seem like the example procedure doesnt need to use a dynamic SQL execution to call TEST_FUNCTION but the actual code that I extracted from does.
    Does Oracle 7 always treat the dynamic SQL command set as some kind of update statement? Is that a bug? I understand that the EXECUTE IMMEDIATE command in Oracle 8i will replace the old command set found in the above examples. Will using the new EXECUTE IMMEDIATE command in Oracle 8i solve this problem?
    Thank you for any help,
    Tony

    In Oracle 7, for a function to be called from a select statement it has to follow the 'purity rule' that it does not modify any database table or package variable.
    Probably you will have to use the compiler directive PRAGMA RESTRICT_REFERENCES (WNDS,WNPS) on your TEST_FUNCTION so that it can be called within a SQL statement.
    This restriction is removed in Oracle 8i onwards.
    Hope this solves your problem.
    Regards

  • Dynamically how to calculate expression through PL/SQL ..?

    My senario like...
    I want to calculate the expression using array values from input parameter and then I want to send that calculated values as a output parameter.
    How to do through PL/SQL..?
    I am passing two parameter.
    1. expression variable value as array,
    2. expression as string
    I want to execute that expression using Execute immediate or any other way through PL/SQL.
    For Example,
    exec myPL_SQLproc(p1,p2)
    p1,p2 = (1,2,3), 'a*(a+10)-b+c'
    p1,p2 = (1,2,3,4,5), '((a+b+c+d+e)+(a-b-c-d-e))*log(a)' here base10 for log(a).
    here p1 is array (pl/sql table type)
    p2 is string (expression: varchar2 type)

    Although I think this is likely to be a bad design decision, you can use something like:
    DECLARE
       TYPE values_tp IS VARRAY(10) OF NUMBER;
       l_values_tp values_tp := values_tp(1,2,3);
       l_expr VARCHAR2(25) := 'a*(a+10)-b+c';
       l_exec VARCHAR2(25);
       l_result NUMBER;
    BEGIN
       FOR i IN 1 .. l_values_tp.COUNT LOOP
          l_expr := REPLACE(l_expr, CHR(96+i), l_values_tp(i));
       END LOOP;
       DBMS_OUTPUT.Put_Line(l_expr);
       EXECUTE IMMEDIATE 'SELECT '||l_expr||' FROM dual' INTO l_result;
       DBMS_OUTPUT.Put_Line('Result is '||l_result);
    END;Minimally, you should check the formula string for things like semi-colons (;) and two consecutive hyphen (--) which could indicate a sql injection attempt. You would also probably need much more error handling.
    TTFN
    John

  • Dynamic SQL and GRANT CREATE ANY TABLE

    hi gurus,
    i have a dynamic SQL in a procedure where a table will be created from an existing table without data.
    strSQL:='create table ' || strTemp || ' as select * from ' || strArc || ' where 1=2';
    execute immediate strSQL;
    without GRANT CREATE ANY TABLE for the user, *"ORA-01031: insufficient privileges"* error during execution.
    Is there a way to tackle this issue without providing GRANT CREATE ANY TABLE privilige?
    many thanks,
    Charles

    ravikumar.sv wrote:
    The problem is not because of dynamic sql...It probably has something to do with dynamic SQL or, more accurately, dynamic SQL within a stored procedure.
    From a SQL*Plus command prompt, you can create a table if your account has the CREATE TABLE privilege either granted directly to it or granted to a role that has been granted to your account. Most people probably have the CREATE TABLE privilege through a role (hopefully a custom "developer role" that has whatever privileges you grant to users that will own objects but potentially through the default RESOURCE role). That is not sufficient to create tables dynamically via a definer's rights stored procedure. Only privileges that are granted directly to the user, not those granted via a role, are visible in that case.
    I expect that the DBAs are granting the CREATE ANY TABLE privilege directly to the account in question rather than through whatever role(s) are being used which is why that appears to solve the problem.
    Justin

  • 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.

  • 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>

  • Insert into using a select and dynamic sql

    Hi,
    I've got hopefully easy question. I have a procedure that updates 3 tables with 3 different update statements. The procedure goes through and updates through ranges I pass in. I am hoping to create another table which will pass in those updates as an insert statement and append the data on to the existing data.
    I am thinking of using dynamic sql, but I am sure there is an easy way to do it using PL/SQL as well. I have pasted the procedure below, and what I'm thinking would be a good way to do it. Below I have pasted my procedure and the bottom is the insert statement I want to use. I am faily sure I can do it using dynamic SQL, but I am not familiar with the syntax.
    CREATE OR REPLACE PROCEDURE ACTIVATE_PHONE_CARDS (min_login in VARCHAR2, max_login in VARCHAR2, vperc in VARCHAR2) IS
    BEGIN
    UPDATE service_t SET status = 10100
    WHERE poid_id0 in
    (SELECT poid_id0 FROM service_t
    WHERE poid_type='/service/telephony'
    AND login >= min_login AND login <= max_login);
    DBMS_OUTPUT.put_line( 'Service Status:' || sql%rowcount);
    UPDATE account_t SET status = 10100
    WHERE poid_id0 IN
    (SELECT account_obj_id0 FROM service_t
    WHERE poid_type = '/service/telephony'
    AND login >= min_login AND login <= max_login);
    DBMS_OUTPUT.put_line( 'Account Status:' || sql%rowcount);
    UPDATE account_nameinfo_t SET title=Initcap(vperc)
    WHERE obj_id0 IN
    (SELECT account_obj_id0 FROM service_t
    WHERE poid_type='/service/telephony'
    AND login >=min_login AND login <= max_login);
    DBMS_OUTPUT.put_line('Job Title:' || sql%rowcount);
    INSERT INTO phone_card_activation values which = 'select a.status, s.status, s.login, to_char(d.sysdate,DD-MON-YYYY), ani.title
    from account_t a, service_t s, account_nameinfo_t ani, dual d
    where service_t.login between service_t.min_login and service_t.max_login
    and ani.for_key=a.pri_key
    and s.for_key=a.pri_key;'
    END;
    Thanks for any advice, and have a good weekend.
    Geordie

    Correct my if I am wrong but aren't these equal?
    UPDATE service_t SET status = 10100
    WHERE poid_id0 in
    (SELECT poid_id0 FROM service_t
    WHERE poid_type='/service/telephony'
    AND login >= min_login AND login <= max_login);
    (update all the records where there id is in the sub-query that meet the WHERE Clause)
    AND
    UPDATE service_t SET status = 10100
    WHERE poid_type='/service/telephony'
    AND login >= min_login AND login <= max_login);
    (update all the records that meet the WHERE Clause)
    This should equate to the same record set, in which case the second update would be quicker without the sub-query.

  • Performance between SQL Statement and Dynamic SQL

    Select emp_id
    into id_val
    from emp
    where emp_id = 100
    EXECUTE IMMEDIATE
    'Select '|| t_emp_id ||
    'from emp '
    'where emp_id = 100'
    into id_valWill there be more impact in performance while using Dynamic SQL?

    CP wrote:
    Will there be more impact in performance while using Dynamic SQL?All SQLs are parsed and executed as SQL cursors.
    The 2 SQLs (dynamic and static) results in the exact same SQL cursor. So both methods will use an identical cursor. There are therefore no performance differences ito of how fast that SQL cursor will be.
    If an identical SQL cursor is not found (a soft parse), the SQL engine needs to compile the SQL source code supplied, into a SQL cursor (a hard parse).
    Hard parsing burns a lot of CPU cycles. Soft parsing burns less CPU cycles and is therefore better. However, no parsing at all is the best.
    To explain: if the code creates a cursor (e.g. INSERT INTO tab VALUES( :1, :2, :3 ) for inserting data), it can do it as follows:
    while More Data Found loop
      parse INSERT cursor
      bind variables to INSERT cursor
      execute INSERT cursor
      close INSERT cursor
    end loopIf that INSERT cursor does not yet exists, it will be hard parsed and a cursor created. Each subsequent loop iteration will result in a soft parse.
    However, the code will be far more optimal as follows:
    parse INSERT cursor
    while More Data Found loop
      bind variables to INSERT cursor
      execute INSERT cursor
    end loop
    close INSERT cursorWith this approach the cursor is parsed (hard or soft), once only. The cursor handle is then used again and again. And when the application is done inserting data, the cursor handle is released.
    With dynamic SQL in PL/SQL, you cannot really follow the optimal approach - unless you use DBMS_SQL (a complex cursor interface). With static SQL, the PL/SQL's optimiser can kick in and it can optimise its access to the cursors your code create and minimise parsing all together.
    This is however not the only consideration when using dynamic SQL. Dynamic SQL makes coding a lot more complex. The SQL code can now only be checked at execution time and not at development time. There is the issue of creating shareable SQL cursors using bind variables. There is the risk of SQL injection. Etc.
    So dynamic SQL is seldom a good idea. And IMO, the vast majority of people that post problems here relating to dynamic SQL, are using dynamic SQL unnecessary. For no justified and logical reasons. Creating unstable code, insecure code and non-performing code.

  • For loops and dynamic sql string syntax

    Hi
    is there a why to loop through a dynamic sql string
    normally you would have
    FOR cur IN (select * from emp) LOOP
    but I have a dynamic sql string called l_sql
    I have tried the following
    FOR cur IN l_sql LOOP
    but I get
    PLS-00456: item 'L_SQL' is not a cursorCompilation failed
    Any ideas?

    You will need to use ref cursors and the OPEN v_rc FOR '<your sql string'> and then loop through it as you would with any other OPEN, LOOP, EXIT WHEN, END LOOP syntax

  • BCP and dynamic SQL

    Hello All,
    Been looking into this for a couple of days, and I keep hitting brick walls, so I'm hoping someone can offer me a bit of inspiration. What I'm trying to do is write a stored procedure that lets the user specify a list of tables, and an output directory, and the SP creates a series of BCP statements that export these tables to comma delimited files.
    This wouldn't be too hard, but I need to output the field headings in the first row of the table (and use quotes as text qualifiers). I'm doing this by looping round sys.columns, pulling out all the fieldnames, creating two select statements, and UNION ALL-ing them together. e.g.......
    select 'FIELD1','FIELD2','FIELD3','FIELD4'
    union all
    select field1,field2,field3,field4 from tablename
    It all works fine until you try it on a table with a lot of columns. Although you can build a big SQL statement in an NVARCHAR(MAX), BCP only appears to read the first 4000 characters of it, so it fails.
    To get round this, I've moved all of the code that builds the big SQL statement to its own stored procedure (i.e. you pass the tablename, and it returns the table with the field names in the first row). Then, I can just call this new SP in my BCP statement, with a couple of parameters. 
    The problem I'm getting is BCP is complaining saying '[Microsoft][SQL Native Client]BCP host-files must contain at least one column'.  I'm setting no count off, and there are no print statements, so I'm assuming this is because the data is getting returned via an exec sp_executesq (although this is a guess). I can't think of a way round this though, as the SQL need to be dynamic.
    alter PROCEDURE [dbo].[sp_QBMultiFileExportGetData]
    @tablename varchar(100),
    @dbname varchar(100)
    AS
    BEGIN
    declare @Execstring as nvarchar(MAX)
    declare @currentfieldname as varchar(100)
    declare @selectlist as varchar(8000)
    declare @fieldnamelist as varchar(8000)
    declare @colnames table
    columnname varchar(100)
    begin
    set nocount on
    set @execstring='select COLUMN_NAME '+
    'from ' + @dbname + '.INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = ''' + @tablename + ''''
    insert into @colnames(columnname)
    exec sp_executesql @execstring
    set @selectlist=''
    set @fieldnamelist=''
    --Loop through fieldnames, and build two strings
    --One for outputting fieldnames and one for selecting the actual data
    while exists(select * from @colnames)
    begin
    select top 1 @currentfieldname=columnname from @colnames
    set @selectlist=@selectlist + 'quotename(['+ @currentfieldname + '],char(34)),'
    set @fieldnamelist=@fieldnamelist + '''' + @currentfieldname + ''' [' +@currentfieldname + '],'
    delete from @colnames where columnname=@currentfieldname
    end
    --remove last quote
    set @selectlist=substring(@selectlist,1,len(@selectlist)-1)
    set @fieldnamelist=substring(@fieldnamelist,1,len(@fieldnamelist)-1)
    --Built string to execute, with fieldnames, and select fields
    set @execstring='select ' + @fieldnamelist  + ' union all select ' + @selectlist + ' from ' + @dbname + '..'  + @tablename
    return exec sp_executesql @execstring
    end
    END
    this returns exactly what I want, but when I try to use it in a BCP statement, I get the error....
    i.e.
    EXEC master..xp_cmdshell 'bcp "exec QCDev.dbo.sp_QBMultiFileExportGetData ''tablename'',''dbname''" queryout C:\\outputfile.txt -T -t","'
    Error = [Microsoft][SQL Native Client]BCP host-files must contain at least one column
    Anyone ever tried this before?

    Hi Guys,
    Thanks for the suggestions. I had been trying to avoid temp tables (don't really like them), but I think eventually, they were the only way to go. Unfortunately, this opened a whole can of scoping worms, and after a couple of hours, its all given me a right headache. However, the good news is I've finally got it working as I wanted.
    I was finding I was having issues using temp tables, as the tables being used were dynamic, so I would have to create them in a dynamic SQL string, and they weren't propagating upwards from child to parent. I seemed to be getting the same problem using global temporary tables too, although I'm not sure why, as they should have worked They seemed to be out of scope by the time the SP that was calling my sp_QBMultiFileExportGetData tried to output the data. This might possibly have been because BCP wasn't seeing the same scope, but I've not tested it fully (and its very possible I was making a mistake).
    The solution was to abandon sp_QBMultiFileExportGetData, and merge the code back into the calling script. However, rather than trying to pass an enormous SQL string to bcp, running it separately with sp_executesql, and dumping the results in a global temp table. Then let bcp just call a 'select * from temptable', to avoid the select statement getting too long. Its not the most elegant solution, but it seems to work fine.
    ALTER PROCEDURE [dbo].[sp_QBMultiFileExport]
    -- Add the parameters for the stored procedure here
    @tablenames varchar(1000), --list of tables to be exported
    @outputpath varchar(1000), --output path ***AS SEEN BY THE SERVER, NOT THE CLIENT***
    @servername varchar(100), --Server where data resides
    @dbname varchar(100), --database name
    @delimiter varchar(1) --output delimiter
    AS
    BEGIN
    declare @Execstring as nvarchar(max)
    declare @currenttable as varchar(100)
    declare @colnames table
    columnname varchar(100)
    declare @currentfieldname as varchar(100)
    declare @selectlist as varchar(max)
    declare @fieldnamelist as varchar(max)
    --Get rid of CRLFs in the tablenames parameter
    set @tablenames=replace(@tablenames,char(10),'')
    set @tablenames=replace(@tablenames,char(13),'')
    --add extra comma to the end of the list (needed later for consistency)
    set @tablenames=@tablenames+','
    --Get first table in the list
    set @currenttable=substring(@tablenames,1,charindex(',',@tablenames)-1)
    while @tablenames<>''
    begin
    --Get a list of fieldnames from syscols
    insert into @colnames(columnname)
    select COLUMN_NAME
    from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = @currenttable
    set @selectlist=''
    set @fieldnamelist=''
    while exists(select * from @colnames)
    begin
    --get first column name
    select top 1 @currentfieldname=columnname from @colnames
    --add to select statement lists
    set @selectlist=@selectlist + 'quotename(['+ @currentfieldname + '],char(34)),'
    set @fieldnamelist=@fieldnamelist + '''' + @currentfieldname + ''' [' +@currentfieldname + '],'
    --remove column from temptable
    delete from @colnames where columnname=@currentfieldname
    end
    --remove last quote from field lists
    set @selectlist=substring(@selectlist,1,len(@selectlist)-1)
    set @fieldnamelist=substring(@fieldnamelist,1,len(@fieldnamelist)-1)
    --check for temp table, and drop if necessary
    IF object_id('tempdb..##MultiFileExportTempTable') IS NOT NULL
    BEGIN
    DROP TABLE ##MultiFileExportTempTable
    END
    --Build list of fieldnames, and select list, unioned together
    --and put the results in temptable
    set @execstring='select ' + @fieldnamelist  + ' into ##MultiFileExportTempTable union all select ' + @selectlist + ' from ' + @dbname + '..'  + @currenttable
    exec sp_executesql @execstring
    --get BCP to pull data back from ##temptable, and dump in file
    set @execstring='EXEC master..xp_cmdshell ''bcp "select * from ##MultiFileExportTempTable" queryout ' + @outputpath + '\' + @currenttable + '.txt' + ' -c -T -t"' + @delimiter + '"'''
    exec sp_executesql @execstring
    --drop tablename from list
    set @tablenames=replace(@tablenames,@currenttable + ',','')
    --if tablenames list is not empty, get the next one
    if @tablenames<>''
    set @currenttable=substring(@tablenames,1,charindex(',',@tablenames)-1)
    else
    set @currenttable=''
    end
    IF object_id('tempdb..##MultiFileExportTempTable') IS NOT NULL
    BEGIN
    DROP TABLE ##MultiFileExportTempTable
    END
    END
    So, you call this with...
    exec dbo.[sp_QBMultiFileExport] 'table1,table2,table3',filepath,servername,dbname,delimiter
    ...and it creates delimited files called table1.txt, table2.txt and table3.txt in the specified folder, with field headings and text qualifiers.
    Many thanks for all your suggestions

  • Dynamic sql and updating cursors

    hi to anyone,
    we use few temporary global tables which will be created on the fly if not present ( the reason is - they are not created by power designer ).
    addressing theses tables is only possible by using dynamic sql via "execute immediate" because they may not be known to the compiler as they are not created yet.
    Now I defined a cursor to walk through the table - using cursor reference "ref cursor". Using this cursor works, but i found no way using this cursor for update. i.e. declaring as .. for update of and later putting it into an execute immediate like " execute immediate 'update ' || w_temp_table || ' set f1 = :1, f2 = :2 where current of ' || w_cursor using w_1, w_2;" It doesnt work if I block this command using "begin / end".
    Does naybody know a solution ?
    thanks in advance
    wilko

    Thanks todd,
    my main purpose has been just using the dynamic cursor for update as I know that this is quite easy and also fast. I didnt concern about locking all rows I walk through. But you are right - at end you will use the most easy way. So what I did because of another cursor problem ( with analytical functions ) - I defined the temporary table before compiling and everything is much more convenient.
    thanks for help
    wilko

  • Dynamic SQL Error -ORA-00904: invalid identifier

    Hello!
    I'm really hoping I can get some fast help on this. In the interest of honesty, this is for a university oracle programming assignment. I've searched everywhere I can for the answer and haven't had any luck.
    Anyway, the problem in a nutshell. I have to write a package to write a text file. The formatting information for the file is held in a table, which has columns to define the various characteristics like justification, padding character and field value.
    RECORDTYPE FIELDNAME FIELDVALUE FIELDSIZE FIELDORDER PADDINGCHAR JUSTIFICATION DATASOURCE
    7 CreditTotal v_credit 10 5 '0' LPAD PROGRAM
    7 RecordType '7' 1 1 ' ' RPAD HARDCODE
    I can build the whole file except this footer. the FieldValue "v_credit" references a variable that has the calculated total of the credit amounts for the file. There are also "v_debit", and "(v_credit-v_debt)" entries.
    My question seems simple... How can I use this VARCHAR2 value from the table, and have it reference the variable within a Dynamic SQL string? If I use the textvalue of the column in the SQL string it gives me the invalid identifier error when it hits the EXECUTE IMMEDIATE statement. There is another row for the header which has "to_char(sysdate,'DDMMYYYY')" in it, and that runs fine. I'm assuming because they are native SQL statements and variables.
    I have tried encapsulating the v_credit in "s, and using dynamica bind variables but had the same problem passing the names to the USING clause.
    The SQL string created by the procedure is: SELECT LPAD(v_credit,10,'0' ) FROM dual
    The full error is:
    ORA-00904: "V_CREDIT": invalid identifier
    ORA-06512: at "BWOOD.PKG_BRIAN", line 108
    ORA-06512: at line 2
    Line 108 is the EXECUTE IMMEDIATE statement
    I would really appreciate someones help! I'm happy to post the procedure I've written, with the caveat that it's sloppy student work and needs cleaning up of all the experimental commented attempts:)
    Edited by: user5426606 on 20-May-2009 03:34 - Added a few more facts.

    Thank you for the fast replies. I'll post a short chunk of code to demonstrate.
    The actual procedure is quite a bit longer, but this should give you the idea.
    PROCEDURE build_dbfile (p_settlement_date IN DATE, p_settlement_key IN VARCHAR2, p_type IN VARCHAR2) AS
    v_sqlString    VARCHAR2(4000) := 'SELECT ';
    v_rectype     NUMBER := 7;
    v_line           LONG;
    v_debit        NUMBER := 0;
    v_credit       NUMBER := 0;
    v_nrRecords    NUMBER := 0;
      CURSOR c_settlement IS... -- to select records for data rows
    -- cursor to select the rows with the file formatting and data info
      CURSOR c_header IS   SELECT   NVL(fieldvalue,fieldname) db_field, <---- selects the data column
                                                   fieldsize,
                                                   NVL(paddingchar, ''' ''') paddingchar,
                                                   NVL(justification,'LPAD') justification,
                                                  datasource
                                      FROM     FSS_DESKBANK_REF
                                      WHERE    recordtype = r_rec_types.recordtype
                                      ORDER BY recordType, fieldorder;
    -- SELECT to get the SUM of datarows for v_credit
      SELECT      SUM(transactionamount)
      INTO      v_credit...
    -- SELECT to get the SUM of datarows for v_debit
      SELECT      SUM(transactionamount)
      INTO      v_debit....
    FOR r_head IN c_header LOOP
    v_sqlString := v_sqlString  || r_head.justification|| '('
                                         || r_head.db_field ||','
                                         || r_head.fieldsize || ','
                                         || r_head.paddingchar || ')';
    v_sqlString := v_sqlString || ' FROM ' || v_tbl_name;
    DBMS_OUTPUT.PUT_LINE('SQL --> '||v_sqlString);
    EXECUTE IMMEDIATE v_sqlString INTO v_line;
    END LOOP;
    DBMS_OUTPUT.PUT_LINE(v_line);
    END build_dbfile;So the loop goes through the table rows, grabs each data value and formatting column, and builds the sql string, which is then passed to the execute statement. The issue is the ones where the datarow contains a reference to v_credit, and the error is generated. ie r_head.db_field contains the string "v_credit"
    Satish, the sql does look like that in the string, but the string is built from the table, not hardcoded. ie v_sqlString = "SELECT LPAD(v_credit,10,'0' ) FROM dual" when it is passed to the EXECUTE IMMEDIATE.
    Edited by: user5426606 on 20-May-2009 05:19

  • Dynamic sql in a trigger ...please help

    HI All,
    I've got a really large table called 'shop' of the form
    id number, product1_cost number, product2_cost number,product3_cost, product4_cost....and so on until product20_cost,
    product1_desc, product2_desc....and so so on until..product20_desc, active, start_date, end_date, usercreated,
    useramended.
    I have now created a new application. The new table is called 'products' which has an id, cost, description, oldproductid, shopid
    I need a trigger on the table shop so that if anyone uses the old application, it automatically creates the product rows in my new table 'products'
    Not all the product fields on the 'shop' table have data so I only want to migrate data if necessary.
    The trigger would do the following:
    1. Loop through all the products, if the product was updated and product number does not exist on 'products.oldproductid' then create a new record in products
    2. If product was updated and product number does exist then simply update the product details.
    I have got the trigger to work with product1. However, I'm finding it difficult to write some sort of dynamic sql that would
    do the same check on all 20 products without having to repeat the code 20 times.
    can someone help?
    CREATE OR REPLACE TRIGGER TR_PRODCOST
    AFTER UPDATE ON SHOP
    FOR EACH ROW
    DECLARE
    v_oldproductid products.oldpackageid%TYPE;
    v_datedl products.datedl%TYPE;
    v_product_sq number;
    v_status number := 1;
    v_cost number(11, 2);
    v_old_pkg number:= :old.product1_cost;
    v_new_pkg number:= :new.product1_cost;
    v_old_desc varchar2(100):= :old.product1_desc;
    v_new_desc varchar2(100):= :new.product1_desc;
    v_old_shop varchar2(10):= :old.shopid;
    v_new_shop varchar2(10):= :new.shopid;
    CURSOR get_newproduct_cur IS
    SELECT p.oldproductid, p.datedl
    FROM products p
    WHERE p.shopid = v_new_shop
    AND p.oldproductid = 1;
    BEGIN
    IF nvl(v_new_pkg, -1) <> nvl(v_old_pkg, -1) THEN
    OPEN get_newproduct_cur;
    FETCH get_newproduct_cur
    INTO v_oldproductid, v_datedl;
    IF get_newproduct_cur%NOTFOUND THEN
    v_oldproductid := null;
    v_datedl := null;
    END IF;
    CLOSE get_newproduct_cur;
    IF v_oldproductid is null THEN
    SELECT SEQ_products.nextval INTO v_product_sq FROM dual;
    INSERT into products p
    (product_ID,
    SHOPID,
    DESCRIPTION,
    COST,
    DATECR,
    USERCR,
    OLDproductID,
    SHORT_DESCRIPTION)
    VALUES
    (v_product_sq,
    v_new_shop,
    v_new_desc,
    v_new_pkg,
    sysdate,
    'OLFORMS',
    1,
    v_new_desc);
    ELSE
    IF v_new_pkg is null THEN
    UPDATE products p
    set p.datedl = sysdate,
    p.cost = 0.00
    WHERE p.shopid = v_new_shop
    AND p.oldproductid = 1;
    ELSE
    UPDATE products p
    set p.cost = v_new_pkg,
    p.datedl = null,
    WHERE p.shopid = v_new_shop
    AND p.oldproductid = 1;
    END IF;
    IF v_new_desc = v_old_desc THEN
    v_status := 1;
    ELSE
    UPDATE products p
    SET p.description = v_new_desc
    WHERE p.shopid = v_new_shop
    AND p.oldproductid = 1;
    END IF;
    END IF;
    ELSE
    END IF;
    END IF;
    END;

    Hi All,
    Thanks about your advice on the relational design. However, this is only a temporary fix. The old shop table was created about 10 years ago by someone else. Our users have to use the old pages for about 2-3 weeks and therefore I need a quick fix that will create the products on the new tables.
    The other problem I have is that another powerbuilder based applicated also uses the same tables and that application is being modified to use the new tables but not until another 3 weeks. To ensure both systems are available in parallel, I have to implement this temporary solution.
    B_Binoy, you seem you have a solution there but I didn't quite get it. I tried putting the whole pl/sql block in a string, replacing the '1' in product 1 using a variable x and then using execute immediate but because of the :new and :old bind variables, it kept giving me errors like 'variables not bound' etc. If you don't mind, please can you expand on your solution?
    Many Thanks

Maybe you are looking for

  • How to find out if AE_init_append_data.xml has been imported or not?

    HI Gurus, Is there a way in CUP to find out if the initial config files have been uploaded or not the AE_init_append_data.xml. There are 2 files which need to be uploaded initially. However the other one uses a clean and insert option. So I think if

  • Connecting Sony Camcorder to MacBook Pro

    I have a new MacBook Pro and I have a Sony Handycam DCR HC38. How do I connect the 2 when there is no Firewire cable on the new computer? Someone please help, it's making me crazy!

  • PS Tables for Documents, Acitivity Relationships

    Hi Frinds We are looking for proper talbes for the following. Can any one help us which are tables to be referred for <b>1.   Documents (this icon we can see in overview screen of WBS elements) 2.  Network Relationship Activity Relationships (Besides

  • I tunes is telling me I have reached the limit for home sharing authorizations

    I tunes is telling me that I have maxed out the number of authorizations I'm allowed for home sharing. How do I fix this? I was just given a powerbook g4. I need to authorize it. Please assist me I'm new to OS X I spend most of my days working with W

  • How to create a Cash Flow Statement?

    Dear all: I am trying to create a Cash Flow Statement, and my approach is to use Dimension formula to calculate on the fly. Is my approach the best practice, or should I use script logic instead? Based on my understanding, if I use Dimension formula,