Retrieve and display a result set using the dynamic sql?

Hi all

How would display a result set in Oracle using the dynamic SQL? Reason being, the table where I'd retrieve and display the result set is a GLOBAL TEMP TABLE created in a stored procedure. If I try to use the loop as usual, the compiler complains that the table does not exist. This makes sense because the compiler does not recognize the table because it is created dynamically. Here is an example:

create or replace PROCEDURE maketemptab IS
sql_stmt VARCHAR2 (500);
OutputString VARCHAR2 (50);

BEGIN
-create temporary table
sql_stmt: = ' CREATE of TABLE TEMPORARY GLOBAL globtemptab (id NUMBER, col1 VARCHAR2 (50))';
EXECUTE IMMEDIATE sql_stmt;
dbms_output.put_line ('... created table ');

-Insert a row into the temporary table
sql_stmt: = "INSERT INTO globtemptab values (1, 'some data of a test')';"
EXECUTE IMMEDIATE sql_stmt;
dbms_output.put_line ('... inserted row ');

-Insert a row into the temporary table
sql_stmt: = ' INSERT INTO globtemptab values (2, "some more test data");
EXECUTE IMMEDIATE sql_stmt;
dbms_output.put_line ('... inserted row ');

-Select the row on temporary table
sql_stmt: = 'SELECT col1 FROM globtemptab WHERE id = 1';
EXECUTE IMMEDIATE sql_stmt INTO outputstring;
dbms_output.put_line ('... selected line: ' | outputstring);

-drop temporary table
sql_stmt: = 'DROP TABLE globtemptab;
EXECUTE IMMEDIATE sql_stmt;
dbms_output.put_line ('... moved table ');

-display the result set
for tabdata loop (select col1 from globtemptab)
dbms_output.put_line ('... test of recovered data are' | tabdata.col1)
end loop;
end;


In short, how to rewrite the SQL below the comment "to display the result set" using the dynamic sql?

Thank you
Amedeo.

Hello

Try this:

CREATE OR REPLACE PROCEDURE maketemptab IS
   sql_stmt     VARCHAR2(500);
   outputstring VARCHAR2(50);
   v_cursor     SYS_REFCURSOR;
   v_col1       VARCHAR2(30);
BEGIN
   -- create temp table
   sql_stmt := 'CREATE GLOBAL TEMPORARY TABLE globtemptab(id NUMBER, col1 VARCHAR2(50))';
   EXECUTE IMMEDIATE sql_stmt;
   dbms_output.put_line('...table created');

   -- insert row into temp table
   sql_stmt := 'INSERT INTO globtemptab values (1, ''some test data'')';
   EXECUTE IMMEDIATE sql_stmt;
   dbms_output.put_line('...row inserted');

   -- insert row into temp table
   sql_stmt := 'INSERT INTO globtemptab values (2, ''some more test data'')';
   EXECUTE IMMEDIATE sql_stmt;
   dbms_output.put_line('...row inserted');

   -- select row from temp table
   sql_stmt := 'SELECT col1 FROM globtemptab WHERE id=1';
   EXECUTE IMMEDIATE sql_stmt
      INTO outputstring;
   dbms_output.put_line('...row selected: ' || outputstring);

   OPEN v_cursor FOR 'SELECT col1 FROM globtemptab';

   LOOP
      FETCH v_cursor
         INTO v_col1;
      EXIT WHEN v_cursor%NOTFOUND;
      dbms_output.put_line('...test data retrieved is' || v_col1);
   END LOOP;
   CLOSE v_cursor;

   -- drop temp table
   sql_stmt := 'DROP TABLE globtemptab';
   EXECUTE IMMEDIATE sql_stmt;
   dbms_output.put_line('...table dropped');
END;
/

Kind regards

Tags: Database

Similar Questions

  • using the dynamic SQL syntax

    I am trying to create a dynamic sql to execute the following statement:

    create the table mytbl_20100901 in select * from matbl double;

    When I try the following error I
    ORA-06550: line 6, column 10:
    PLS-00103: encountered the symbol "SELECT" at the expected in the following way:

    ;;;;;;;;;;;;;;;;;;;;;;;;;;;
    declare
    sql_cmd varchar2 (1000);

    Start

    sql_cmd: = select "create table mytbl_ | To_char (sysdate, 'YYYYMMDD') | ' in select * from matbl ' double.

    immediately run sql_cmd;

    end;
    ;;;;;;;;;;;;;;;;;;;;;;;;;

    How to fix the sql_cmd assignment statement?

    Thank you.

    Hello

    user1035690 wrote:
    I am trying to create a dynamic sql to execute the following statement:

    create the table mytbl_20100901 in select * from matbl double;

    When I try the following error I
    ORA-06550: line 6, column 10:
    PLS-00103: encountered the symbol "SELECT" at the expected in the following way:

    ;;;;;;;;;;;;;;;;;;;;;;;;;;;
    declare
    sql_cmd varchar2 (1000);

    Start

    sql_cmd: = select "create table mytbl_ | To_char (sysdate, 'YYYYMMDD') | ' in select * from matbl ' double.

    immediately run sql_cmd;

    end;
    ;;;;;;;;;;;;;;;;;;;;;;;;;

    How to fix the sql_cmd assignment statement?

    Thank you.

    The dual table is not necessary a lot in PL/SQL.
    You can simply say:

    sql_cmd := 'create table mytbl_' || TO_CHAR(sysdate, 'YYYYMMDD') || ' as select * from mytbl';
    dbms_output.put_line (sql_cmd || ' <= sql_cmd');
    -- EXECUTE IMMEDIATE sql_cmd;
    

    During the development of the dynamic SQL statements, I suggest that you post the command rather than run it first.
    When it seems correct, then a comment instructions EXECUTE IMMEDIATE.
    Before the Production code, remove or comment the call to out_line.

  • Tables created in a stored procedure cannot be used with dynamic SQL? The impact?

    There is a thread on the forum which explains how to create tables within a stored procedure (How to create a table in a stored procedure , however, it does create a table as such, but not how to use it (insert, select, update, etc.) the table in the stored procedure.) Looking around and in the light of the tests, it seems that you need to use dynamic SQL statements to execute ddl in a stored procedure in Oracle DB. In addition, it also seems that you cannot use dynamic SQL statements for reuse (insert, select, update, etc.) the table that was created in the stored procedure? Is this really the case?

    If this is the case, I am afraid that if tables cannot be 'created and used"in a stored procedure using the dynamic SQL, as is the case with most of the servers of DB dynamic SQL is not a part of the implementation plan and, therefore, is quite expensive (slow). This is the case with Oracle, and if yes what is the performance impact? (Apparently, with Informix, yield loss is about 3 - 4 times, MS SQL - 4 - 5 times and so on).

    In summary, tables created within a stored procedure cannot be 'used' with dynamic SQL, and if so, what is the impact of performance as such?

    Thank you and best regards,
    Amedeo.

    Published by: AGF on March 17, 2009 10:51

    AGF says:
    Hi, Frank.

    Thank you for your response. I understand that the dynamic SQL is required in this context.

    Unfortunately, I am yet to discover "that seeks to" using temporary tables inside stored procedures. I'm helping a migration from MySQL to Oracle DB, and this was one of the dilemmas encountered. I'll post what is the attempt, when more.

    In Oracle, we use [global temporary Tables | http://www.psoug.org/reference/OLD/gtt.html?PHPSESSID=67b3adaeaf970906c5e037b23ed380c2] aka TWG these tables need only be created once everything like a normal table, but they act differently when they are used. The data inserted in TWG will be visible at the session that inserted data, allowing you to use the table for their own temporary needs while not collide with them of all sessions. The data of the TWG will be automatically deleted (if not deleted programmatically) when a) a commit is issued or b) the session ends according to the parameter that is used during the creation of the TWG. There is no real need in Oracle to create tables dynamically in code.

    I noticed that many people say that the "Creation of the tables within a stored procedure" is not a good idea, but nobody seems necessarily explain why? Think you could elaborate a little bit? Would be appreciated.

    The main reason is that when you come to compile PL/SQL code on the database, all explicit references to tables in the code must correspond to an existing table, otherwise a djab error will occur. This is necessary so that Oracle can validate the columns that are referenced, the data types of those columns etc.. These compilation controls are an important element to ensure that the compiled code is as error free as possible (there is no accounting for the logic of programmers though ;)).

    If you start to create tables dynamically in your PL/SQL code, so any time you want to reference this table you must ensure that you write your SQL queries dynamically too. Once you start doing this, then Oracle will not be able to validate your SQL syntax, check the types of data or SQL logic. This makes your code more difficult to write and harder to debug, because inevitably it contains errors. It also means that for example if you want to write a simple query to get that one out in a variable value (which would take a single line of SQL with static tables), you end up writing a dynamic slider all for her. Very heavy and very messy. You also get the situation in which, if you create tables dynamically in the code, you are also likely to drop tables dynamically in code. If it is a fixed table name, then in an environment multi-user, you get in a mess well when different user sessions are trying to determine if the table exists already or is the last one to use so they can drop etc. What headache! If you create tables with table names, then variable Dynamics not only make you a lot end up creating (and falling) of objects on the database, which can cause an overload on the update of the data dictionary, but how can ensure you that you clean the tables, if your code has an exception any. Indeed, you'll find yourself with redundant tables lying around on your database, may contain sensitive data that should be removed.

    With the TWG, you have none of these issues.

    Also, what is the impact on the performance of the dynamic SQL statements in Oracle? I read some contrasting opinions, some indicating that it is not a lot of difference between static SQL and SQL dynamic in more recent versions of Oracle DB (Re: why dynamic sql is slower than static sql is this true?)

    When the query runs on the database, there will be no difference in performance because it is just a request for enforcement in the SQL engine. Performance problems may occur if your dynamic query is not binding variable in the query correctly (because this would cause difficult analysis of the query rather than sweet), and also the extra time, to dynamically write the query running.

    Another risk of dynamic query is SQL injection which may result in a security risk on the database.

    Good programming will have little need for the tables of dynamically created dynamically or SQL.

  • How to use transfer windows for xp to xp. When I plug usb computers are delivered to the top with the same screen and when I try to use the transfer to the new computer, it just said information gathering and sits for hours

    How to use transfer windows for xp to xp.  When I plug usb computers are delivered to the top with the same screen and when I try to use the transfer to the new computer, it just said information gathering and sits for hours

    Hello, welcome.

    The process is automatic and the maximum transfer rate should be about 20 GB/HR. If the process crashes during that long of a time, it's probably because of something internal rather something you're doing wrong.
    For reference purposes, I included this link. It goes into the details of the migration from XP to Vista (and the basic steps you follow). The instructions are for migrating to Vista via the network, but you can easily follow the steps and choose a different option for your specific installation.
    For both machines, I recommend you to prepare for the transfer using the following procedure:
    1. click on START > run
    2 type "msconfig" (without the quotes) and press enter
    3. go to the "Startup" tab and uncheck all the entries displayed
    4. click on 'Apply' at the bottom right
    DO NOT RESTART YOUR COMPUTER AGAIN
    5. click on START > run
    6. Type "cmd" (without the quotes). Right-click on the result at the top of the menu START and select 'run as administrator '.
    7. type chkdsk /r and press enter
    8 allow the system to attempt disassembly of the volume
    9. allow the system to plan restarting
    10. restart your computer
    11 let checkdisk analyze the file system on your hard drive
    12. Once completed, perform the same steps on the other machine
    13. Once completed, repeat the transfer

    Let us know what happens
    Thank you!

    Ryan Thieman
    Microsoft Answers Support Engineer
    Visit our Microsoft answers feedback Forum and let us know what you think.

  • Toshiba 32EL800A - message "Please re - set using the menu.

    Hello
    Got a Toshiba 32EL800A - and when I turn there is a telling message "Please re - set using the menu.

    When I try to tune, it cannot find all the channels.

    Sure that's not the antenna he worked 24 hours ago, and there is no weather conditions that would have affected the antenna.

    Any ideas?

    Thank you
    AJ

    Hello

    In my opinion, you need to reset the default settings and should start the search of channel once more.
    Make sure you use the right settings (digital or analog tuner)

  • I'm unable to connect to the internet and I also can not use the WinXP system restore.

    No internet connection and I also can not use the WinXP system restore because it gives me an error at the 'end' which said: it cannot be restored to an earlier date.  I run AntiMalware bytes and StopZilla and erased all that they found.  Now I can't even connect to the internet.  When I go to the command prompt, it gives me an error contact the Support of MS that I know means I have a virus or a trojan that I should just get a time out?  My other PC on the same network is fine and connected.  The NETWORK card is fine, just does not know how to get rid of what it is, I have and to top it all impossible to connect to the internet to try all of the tools that can help.  Someone at - it ideas?

    The error you get at the end of the restoration of the system is typical of some anti-virus programs (Norton, especially) that interfere with the restoration of the system.  Try to start your computer in Mode safe (on several occasions, key to tap F8 while your computer starts) and run safe mode system restore.

    Additional information is necessary to treat your network problem.  Try to bring up a command prompt (start-> Run-> "cmd") or if it does not, try (start-> Run-> "command.com") and enter the command:
    ipconfig/all
    and after the info that appears in the State resulting.

    Also, check the logs of your system related errors (start-> Run-> "eventvwr.msc") and click on 'System' in the left column.

    HTH,
    JW

  • I got a notification saying "password requirement: you must change your secret code in 56 minutes"I panicked and entered my access code using the little box? ". I ' t mess up?

    I got a notification saying "password requirement: you must change your secret code in 56 minutes"I panicked and entered my access code using the little box? ". I ' t mess up?

    Yes. You may be victim of a scam, except if you are connected to your business with this requirement.

    Change your password immediately below:

    https://appleid.apple.com.

  • I was on facebook and remove an icon by using the right-click menu, but then all my photos and pictures of profile, could no longer be seen. I was able to view them in the browser, so it's something I've done in Firefox. How can I unlock a site? "

    I was on facebook and remove an icon by using the right-click menu, but then all my photos and pictures of profile, could no longer be seen. I was able to view them in the browser, so it's something I've done in Firefox. How can I unlock a site?

    If you select that right click menu context then you block all images from this area and not a specific image, so do not use that.

    • Check exceptions in tools > Options > content: Load Images > Exceptions (for example sphotos.ak.fbcdn.net)

    You can use the following steps to check if the images are blocked:

    • Click on the "More information" button to open the "Page Info" with the Security tab selected (also accessible via "tools > Page Info").
    • Go to the Media of the window tab "tools > Page Info.
    • Select the first link of the image and scroll down through the list with the arrow down.
    • If an image in the list is grayed out and there is a check mark in the box "block Images of..." and remove this mark to unlock the images from this area.
  • My spellchecker of Firefox doesn't seem to work; in fact I don't know that there is. I have a hotmail account, and when I try to use the spelling corrector for hotmail I get a message saying that I am using a browser with a built-in spellchecker. Where De

    My spellchecker of firefox doesn't seem to work; That's assuming that it exists at all. For example, when I misspell a Word when you compose an email using hotmail and I try to correct using the spell checker of hotmail, I get a message saying that I am using a browser that has of own built-in spellcheck. If it is integrated, how the hell can I find?

    This has happened

    Each time Firefox opened

    Is as far as I know, always

    You must install a spelling dictionary, only the US version comes with a dictionary.
    https://addons.Mozilla.org/en-us/Firefox/language-tools/

  • I have HP PSC 1610 printer, and until recently, it worked fine. Now it prints very slowly and I'm unable to use the internet, although it is printer.

    I have HP PSC 1610 printer, and until recently, it worked fine. Now it prints very slowly and I'm unable to use the internet, although it is printer. What could be the problem and how can I fix it?

    Hi Dee,

    Please contact Technical Support for assistance with your printer HP: http://www8.hp.com/us/en/support-drivers.html.

    Good luck!

    Kosh

  • Compaq: Hi I have a compaq mini 110 I forgot the passwword and it prevents me from using the machines

    Hi I have a compaq mini 110 I forgot the passwword and it prevents me from using the machines please help this serial number is

    IT SHOWS THE FAILURE OF THE SYSTEM ORDER CNU9418FNF FATAL ERROR PASSWORD CHECKING

    @wisejohn80

    Enter: e9lov3u898 (3rd character is a lowercase L)

    Kind regards

    DP - K

  • I tried to format the C drive and then reinstall Windows Vista using the windows reinstall disk but I couldn't start in it.

    * Original title: reinstalling Windows Vista

    I tried to format the C drive and then reinstall Windows Vista using the windows reinstall disk but I couldn't start in it. I restarted my computer, press the F12 key and selected boot from cd/dvd, but the computer still started in windows. My computer is Dell. If there is no solution, it is possible to reinstall windows without using the disc?

    Hello

    Here are the options of relocation:

    How ro reinstall from the Dell recovery partition:

    http://www.Dell.com/support/troubleshooting/us/en/04/KCS/KcsArticles/ArticleView?c=us&l=en&s=BSD&docid=DSN_336966

    Reinstalling the printer Dell supplied disk:

    http://www.Dell.com/support/troubleshooting/us/en/19/KCS/KcsArticles/ArticleView?c=us&l=en&s=DHS&docid=DSN_339949

    ______________________________________________

    You can also borrow and use a Microsoft Vista DVD, which contains the files for the different editions of Vista (Home Basic, Home Premium, Business and Ultimate) must be installed. The product key on your computer / Laptop box determines what Edition is installed.

    Other manufacturers recovery DVDs are should not be used for this purpose.

    And you need to know the version of 'bit' for Vista, as 32-bit and 64-bit editions come on different DVDs

    Here's how to do a clean install of Vista using a DVD of Vista from Microsoft:

    "How to do a clean install and configure with a full Version of Vista '

    http://www.Vistax64.com/tutorials/117366-clean-install-full-version-Vista.html

    And once the operating system is installed, go to your computer manufacturer's website and get the latest drivers for your particular model or laptop computer.

    And phone Activation may be necessary when you use the above installation method.

    "How to activate Vista normally and by Activation of the phone '

    http://www.Vistax64.com/tutorials/84488-activate-Vista-phone.html

    See you soon.

  • I have saved via a website magazine and am now unable to disconnect! It is an interactive Web site, and I am unable to use the functions, so want to close your session, as there is no button 'unsubscribe '.

    I have saved via a website magazine and am now unable to disconnect! It is an interactive Web site, and I am unable to use the functions, so want to close your session, as there is no button 'unsubscribe '. Thanks for any info provided.

    You should contact the website of the magazine for assistance.  This isn't a Windows, or a problem of Microsoft.

  • Problems with clicking and scrolling when you are using the mouse in IE

    Separated from this thread.

    Original title:

    Problems with clicking and scrolling when you are using the mouse

    I have the same problem.  My touchscreen responds but my touchpad and mouse are unable to save a click in IE.  I need to reboot to rectify.  It seems to be more common when the laptop comes out of fashion 'sleep'.   I tried all the steps above, everything is up-to-date.

    Hello Fred,.

    Thanks for the reply.

    I appreciate your efforts to resolve the issue.

    I would suggest trying the following methods and check if it helps.

    Method 1:
    Run the hardware and devices Troubleshooter and check. Please follow these steps:

    a. press Windows + W keys, type Troubleshooting in the search box and press on Enter.
    b. click on 'show all' and then click 'hardware and devices'.
    c. click 'Next' and then follow the on-screen instructions.

    If this does not help, then use method 2.

    Method 2:
    Start your computer in safe mode and check the number.
    Refer to this article:
    Start settings for Windows (including safe mode)
    http://Windows.Microsoft.com/en-us/Windows-8/Windows-startup-settings-including-safe-mode

    I hope this information helps.

    Please let us know if you need more help.

    Thank you

  • I have a copy of CS5 that is bought and paid for, has been installed and works, until I started using the creative cloud. Now it is considered as a trial, and when I enter the correct serial number it says it is invalid.

    I have a copy of CS5 that is bought and paid for, has been installed and works, until I started using the creative cloud. Now it is considered as a trial, and when I enter the correct serial number it says it is invalid.

    Cloud of reading resumes https://forums.adobe.com/thread/2089127 for ideas (see answer #1).

Maybe you are looking for