Best way to write Pl/Sql

Dear all,
Can someone say the best way writing below stored proc:
procedure missing_authorized_services is
v_truncate_sql varchar2(200);
v_sql varchar2(2000);
BEGIN
v_truncate_sql := 'truncate table missing_authorized_services';
     execute immediate v_truncate_sql;
     commit;
v_sql := 'INSERT into missing_authorized_services select distinct trim(service_group_Cd) as service_group_Cd, trim(service_cd) as service_cd from stage_1_mg_service_request
where (service_group_cd, service_cd) not in (
                    select distinct service_group_cd, service_cd from stage_3_servcd_servgrp_dim)';
execute immediate v_sql;
     commit;
END missing_authorized_services;
/* I am doing select from table and then try to Insert into a different table the result set */
Please guide,
Thanks
J

Hi,
The best way to write PL/SQL (or any code) is in very small increments.
Start with a very simple procedure that does something (anything), just enough to test that it's working.
Add lots of ouput statments so you can see what the procedure is doing. Remember to remove them after testing is finished.
For example:
CREATE OR REPLACE procedure missing_authorized_services IS
        v_truncate_sql  VARCHAR2 (200);
BEGIN
     v_truncate_sql := 'truncate table missing_authorized_services';
     dbms_output.put_line (  v_truncate_sql
                    || ' = v_truncate_sql inside missing_authorized_services'
END      missing_authorized_services;If you get any errors (for example, ORA-00955, becuase you're trying to give the same name to a procedure that you're already using for a table), then fix the error and try again.
When it worls perfectly, then add another baby step. For example, you might add the one line
EXECUTE IMMEDIATE v_truncate_sql;and test again.
Don't use dynamic SQL (EXECUTE IMMEDIATE) unless you have to.
Is there any reason to use dynamic SQL for the INSERT?

Similar Messages

  • Best way to write this sql ?

    Please let me know best way to write this SQL.
    select col1, count(*)
    from TableA
    group by col1
    having count(*) =
    (select max(vals)
    from
    select col1, count(*) as vals
    from TableA
    group by col1
    having count(*) > 1
    )

    post EXPLAIN PLAN
    SELECT col1,
           COUNT(*)
    FROM   tablea
    GROUP  BY col1
    HAVING COUNT(*) = (SELECT MAX(vals)
                       FROM   (SELECT col1,
                                      COUNT(*) AS vals
                               FROM   tablea
                               GROUP  BY col1
                               HAVING COUNT(*) > 1))

  • What is a best way to write SQL ?

    Sample Case
    drop table t;
    drop table b;
    create table t ( a varchar2(4), b number, c varchar2(1));
    insert into t values ('A00', 10, 'R');
    insert into t values ('A01', 11, 'R');
    insert into t values ('A02', 12, 'R');
    insert into t values ('A03', 13, 'R');
    insert into t values ('A00', 10, 'P');
    insert into t values ('A01', 11, 'P');
    insert into t values ('A02', 12, 'P');
    insert into t values ('A03', 13, 'P');
    commit;
    create table b ( j varchar(4), k varchar2(1), l varchar2(5), m number(3), n varchar2(5), o number(3));
    insert into b values ('A00', 'P', 'FIXED', 100, 'FLOAT', 60);
    insert into b values ('A01', 'P', 'FIXED', 101, 'FIXED', 30);
    insert into b values ('A02', 'R', 'FLOAT', 45, 'FLOAT', 72);
    insert into b values ('A03', 'R', 'FIXED', 55, 'FLOAT', 53);
    commit;
    10:19:13 SQL> select * from t;
    A B C
    A00 10 R
    A01 11 R
    A02 12 R
    A03 13 R
    A00 10 P
    A01 11 P
    A02 12 P
    A03 13 P
    8 rows selected.
    10:19:19 SQL> select * from b;
    J K L M N O
    A00 P FIXED 100 FLOAT 60
    A01 P FIXED 101 FIXED 30
    A02 R FLOAT 45 FLOAT 72
    A03 R FIXED 55 FLOAT 53
    1/     In table t each reference having 2 records one with P another is with R
    2/     In table b each refrence merged into single record and there are many records which are not existing in table t
    3/      both t and j tables can be joined using a = j
    4/     If from table t for a reference indicator is 'P' then if have to pick up l and m columns, if it is 'R' then I have to pick up n and o columns
    5/     I want output in following format
    A00     P     FIXED          100
    A00     R     FLOAT          60
    A01     P     FIXED          101
    A01     R     FIXED          30
    A02     P     FLOAT          72
    A02     R     FLOAT          45
    A03     P     FLOAT          53
    A03     R     FIXED          55
    6/     Above example is a sample ouput, In above example I have picked up only l,m,n,o columns, but in real example there are many columns ( around 40 ) to be selected. ( using "case when" may not be practical )
    Kindly suggest me what is a best way to write SQL ?
    thanks & regards
    pjp

    Is this?
    select b.j,t.c as k,decode(t.c,'P',l,n) as l,decode(t.c,'P',m,o) as m
    from t,b
    where t.a=b.j
    order by j,k
    J K L M
    A00 P FIXED 100
    A00 R FLOAT 60
    A01 P FIXED 101
    A01 R FIXED 30
    A02 P FLOAT 45
    A02 R FLOAT 72
    A03 P FIXED 55
    A03 R FLOAT 53
    8 rows selected.
    or is this?
    select b.j,t.c as k,decode(t.c,b.k,l,n) as l,decode(t.c,b.k,m,o) as m
    from t,b
    where t.a=b.j
    order by j,k
    J K L M
    A00 P FIXED 100
    A00 R FLOAT 60
    A01 P FIXED 101
    A01 R FIXED 30
    A02 P FLOAT 72
    A02 R FLOAT 45
    A03 P FLOAT 53
    A03 R FIXED 55
    8 rows selected.

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

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

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

  • Best way to write SELECT statement

    Hi,
    I am selecting fields from one table, and need to use two fields on that table to look up additional fields in two other tables.
    I do not want to use a VIEW to do this. 
    I need to keep all records in the original selection, yet I've been told that it's not good practice to use LEFT OUTER joins.  What I really need to do is multiple LEFT OUTER joins.
    What is the best way to write this?  Please reply with actual code.
    I could use 3 internal tables, where the second 2 use "FOR ALL ENTRIES" to obtain the additional data.  But then how do I append the 2 internal tables back to the first?  I've been told it's bad practice to use nested loops as well.
    Thanks.

    Hi,
    in your case having 2 internal table to update the one internal tables.
    do the following steps:
    *get the records from tables
    sort: itab1 by key field,  "Sorting by key is very important
          itab2 by key field.  "Same key which is used for where condition is used here
    loop at itab1 into wa_tab1.
      read itab2 into wa_tab2     " This sets the sy-tabix
           with key key field = wa_tab1-key field
           binary search.
      if sy-subrc = 0.              "Does not enter the inner loop
        v_kna1_index = sy-tabix.
        loop at itab2 into wa_tab2 from v_kna1_index. "Avoiding Where clause
          if wa_tab2-keyfield <> wa_tab1-key field.  "This checks whether to exit out of loop
            exit.
          endif.
    ****** Your Actual logic within inner loop ******
       endloop. "itab2 Loop
      endif.
    endloop.  " itab1 Loop
    Refer the link also you can get idea about the Parallel Cursor - Loop Processing.
    http://wiki.sdn.sap.com/wiki/display/Snippets/CopyofABAPCodeforParallelCursor-Loop+Processing
    Regards,
    Dhina..

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

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

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

  • Best way to write an Wrapper class around a POJO

    Hi guys,
    What is the best way to write an Wrapper around a Hibernate POJO, given the latest 2.2 possibilities? The goal is, of course, to map 'regular' Java Bean properties to JavaFX 2 Properties, so that they can be used in GUI.
    Thanks!

    what about this:
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.property.StringProperty;
    public class PersonPropertyWrapper {
         private StringProperty firstName;
         private StringProperty lastName;
         private Person _person;
         public PersonPropertyWrapper(Person person) {
              super();
              this._person = person;
              firstName = new SimpleStringProperty(_person.getFirstName()) {
                   @Override
                   protected void invalidated() {
                        _person.setFirstName(getValue());
              lastName = new SimpleStringProperty(_person.getLastName()) {
                   @Override
                   protected void invalidated() {
                        _person.setLastName(getValue());
         public StringProperty firstNameProperty() {
              return firstName;
         public StringProperty lastNameProperty() {
              return lastName;
         public static class Person {
              private String firstName;
              private String lastName;
              public String getFirstName() {
                   return firstName;
              public void setFirstName(String firstName) {
                   this.firstName = firstName;
              public String getLastName() {
                   return lastName;
              public void setLastName(String lastName) {
                   this.lastName = lastName;
         public static void main(String[] args) {
              Person p = new Person();
              p.setFirstName("Jim");
              p.setLastName("Green");
              PersonPropertyWrapper wrapper = new PersonPropertyWrapper(p);
              wrapper.firstNameProperty().setValue("Jerry");
              System.out.println(p.getFirstName());
    }Edited by: 906680 on 2012-7-27 上午10:56

  • What is the best way to write 10 channels of data each sampled at 4kHz to file?

    Hi everyone,
    I have developed a vi with about 8 AI channels and 2 AO channels... The vi uses a number of parallel while loops to acquire, process, and display continous data.. All data are read at 400 points per loop interation and all synchronously sampled at 4kHz...
    My questions is: Which is the best way of writing the data to file? The "Write Measurement To File.vi" or low-level "open/create file" and "close file" functions? From my understanding there are limitations with both approaches, which I have outlines below..
    The "Write Measurement To File.vi" is simple to use and closes the file after each interation so if the program crashes not all data would necessary be lost; however, the fact it closes and opens the file after each iteration consumes the processor and takes time... This may cause lags or data to be lost, which I absolutely do not want..
    The low-level "open/create file" and "close file" functions involves a bit more coding, but does not require the file to be closed/opened after each iteration; so processor consumption is reduced and associated lag due to continuous open/close operations will not occur.. However, if the program crashes while data is being acquired ALL data in the buffer yet to be written will be lost... This is risky to me...
    Does anyone have any comments or suggestions about which way I should go?... At the end of the day, I want to be able to start/stop the write to file process within a running while loop... To do this can the opn/create file and close file functions even be used (as they will need to be inside a while loop)?
    I think I am ok with the coding... Just the some help to clarify which direction I should go and the pros and cons for each...
    Regards,
    Jack
    Attachments:
    TMS [PXI] FINAL DONE.vi ‏338 KB

    One thing you have not mentioned is how you are consuming the data after you save it.  Your solution should be compatible with whatever software you are using at both ends.
    Your data rate (40kS/s) is relatively slow.  You can achieve it using just about any format from ASCII, to raw binary and TDMS, provided you keep your file open and close operations out of the write loop.  I would recommend a producer/consumer architecture to decouple the data collection from the data writing.  This may not be necessary at the low rates you are using, but it is good practice and would enable you to scale to hardware limited speeds.
    TDMS was designed for logging and is a safe format (<fullDisclosure> I am a National Instruments employee </fullDisclosure> ).  If you are worried about power failures, you should flush it after every write operation, since TDMS can buffer data and write it in larger chunks to give better performance and smaller file sizes.  This will make it slower, but should not be an issue at your write speeds.  Make sure you read up on the use of TDMS and how and when it buffers data so you can make sure your implementation does what you would like it to do.
    If you have further questions, let us know.
    This account is no longer active. Contact ShadesOfGray for current posts and information.

  • Best way to write readable code?

    So I'm waist deep in building my GUI by hand and it occurs to me that I'm probably not doing this the best way possible. What I have now is listed below and I was thinking that other possibilities would be to write other methods like initMainFrame() and initSearchPanel() and such that would be called from initComponents() (though I would have to either put the objects outside of those methods, probably declared immediately above the method declaration for readability, or somehow make them class scope that're declared within a method which I think I've seen somewhere, but have been unable to reproduce) or to make new class files that handle this.
    So any comments on my ideas (good/bad/etc) or insight on how you structure your code when making a GUI would be much appreciated.
        public static void initComponents() {
            // main frame
            JFrame mainFrame = new JFrame("CookBook");
            Dimension d1 = new Dimension(255, 255);
            //mainFrame.setSize(d1);
            BorderLayout mainLayout = new BorderLayout();
            mainFrame.setLayout(mainLayout);
            mainFrame.setPreferredSize(d1);
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // end main frame
            // menu
            JMenuBar menuBar = new JMenuBar();
            JMenu file = new JMenu("File") ;
            JMenuItem exit = new JMenuItem("Exit");
            file.add(exit);
            menuBar.add(file);
            mainFrame.setJMenuBar(menuBar);
            // end menu
            // start search bar
            JPanel search = new JPanel();
            SpringLayout searchLayout = new SpringLayout();
            search.setLayout(searchLayout);
            JLabel nameLabel = new JLabel("Name: ");
            JTextField name = new JTextField(10);
            searchLayout.putConstraint(SpringLayout.SOUTH, nameLabel, 0, SpringLayout.SOUTH, name);
            searchLayout.putConstraint(SpringLayout.WEST, nameLabel, PADDING, SpringLayout.WEST, search);
            searchLayout.putConstraint(SpringLayout.WEST, name, PADDING, SpringLayout.EAST, nameLabel);
            searchLayout.putConstraint(SpringLayout.NORTH, name, PADDING, SpringLayout.NORTH, search);
            search.add(nameLabel);
            search.add(name);
            Vector<String> initCatValue = new Vector<String>(1);
            initCatValue.add("Category");
            JComboBox category = new JComboBox(initCatValue);
            category.setEditable(true);
            searchLayout.putConstraint(SpringLayout.WEST, category, PADDING, SpringLayout.WEST, search);
            searchLayout.putConstraint(SpringLayout.NORTH, category, PADDING, SpringLayout.SOUTH, name);
            search.add(category);
            mainFrame.add(search);
            // end search bar
            // status bar
            JPanel status = new JPanel();
            FlowLayout statusLayout = new FlowLayout(FlowLayout.RIGHT);
            status.setLayout(statusLayout);
            JProgressBar progressBar = new JProgressBar();
            status.add(progressBar);
            mainFrame.add(BorderLayout.SOUTH, status);
            // end status bar
            mainFrame.pack();
            mainFrame.setVisible(true);
        }

    or somehow make them class scope that're declared within a method which I think I've seen somewhere, but have been unable to reproduceIf this is your problem then here is one method:
    public class GUI{
    JFrame mainFrame;
    public static void initComponents() {
            initMainFrame();
            initMenu();
            initSearchPanel();
            initStatusBar();
            mainFrame.pack();
            mainFrame.setVisible(true);
    private void initMainFrame(){
           // main frame
            JFrame mainFrame = new JFrame("CookBook");
            Dimension d1 = new Dimension(255, 255);
            //mainFrame.setSize(d1);
            BorderLayout mainLayout = new BorderLayout();
            mainFrame.setLayout(mainLayout);
            mainFrame.setPreferredSize(d1);
            mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            // end main frame
    private void initMenu(){
           // menu
            JMenuBar menuBar = new JMenuBar();
            JMenu file = new JMenu("File") ;
            JMenuItem exit = new JMenuItem("Exit");
            file.add(exit);
            menuBar.add(file);
            mainFrame.setJMenuBar(menuBar);
            // end menu
    private void initSearchPanel(){
          // start search bar
            JPanel search = new JPanel();
            SpringLayout searchLayout = new SpringLayout();
            search.setLayout(searchLayout);
            JLabel nameLabel = new JLabel("Name: ");
            JTextField name = new JTextField(10);
            searchLayout.putConstraint(SpringLayout.SOUTH, nameLabel, 0, SpringLayout.SOUTH, name);
            searchLayout.putConstraint(SpringLayout.WEST, nameLabel, PADDING, SpringLayout.WEST, search);
            searchLayout.putConstraint(SpringLayout.WEST, name, PADDING, SpringLayout.EAST, nameLabel);
            searchLayout.putConstraint(SpringLayout.NORTH, name, PADDING, SpringLayout.NORTH, search);
            search.add(nameLabel);
            search.add(name);
            Vector<String> initCatValue = new Vector<String>(1);
            initCatValue.add("Category");
            JComboBox category = new JComboBox(initCatValue);
            category.setEditable(true);
            searchLayout.putConstraint(SpringLayout.WEST, category, PADDING, SpringLayout.WEST, search);
            searchLayout.putConstraint(SpringLayout.NORTH, category, PADDING, SpringLayout.SOUTH, name);
            search.add(category);
            mainFrame.add(search);
            // end search bar
      private void initStatusBar(){
             // status bar
            JPanel status = new JPanel();
            FlowLayout statusLayout = new FlowLayout(FlowLayout.RIGHT);
            status.setLayout(statusLayout);
            JProgressBar progressBar = new JProgressBar();
            status.add(progressBar);
            mainFrame.add(BorderLayout.SOUTH, status);
            // end status bar
    }There can many other methods to solve this same problem... choose anyone which suits you.
    Thanks!

  • Best way to write stream to OutputStream?

    Hi, I need to write a string into an OutputStream (socket). I am a little confused how is the best way (most elegant, efficient) to do it.
    Should I use a OutputStreamWriter? Sometimes, I also need to write raw bytes directly.
    Currently, I am using:
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(output);
    socket.write(output.toByteArray(), 0 , output.size());
    I would appreciate some oppinions.
    Thanks

    Hi, I need to write a string into an OutputStream
    (socket). I am a little confused how is the best way
    (most elegant, efficient) to do it.
    Should I use a OutputStreamWriter?Yes.
    Sometimes, I also need to write raw bytes directly.But does it happen in the same method? If so, you might need to re-design.
    Currently, I am using:
    ByteArrayOutputStream output = new
    ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(output);
    socket.write(output.toByteArray(), 0 ,
    output.size());What's the BAOS good for? Why not String.getBytes(), if you have to use the bytes?

  • Best way to write specific information to a file

    Hi there,
    I'm looking to write specific information from my program to 2 separate files.
    Before the program runs, it asks the operator for their info (name, password, run ID #, a couple safety checkboxes).
    So, I would like the first file to record log-in information (i.e. The operator's name, the date and time they accessed the program, and the Run ID #) all in a spreadsheet.
    I would like the second file to record data from the different components of the program ( 2 tank levels, a flow meter, and run ID #) in another spreadsheet.
    Any thoughts on the best way to do this? I've looked at using arrays to organize the info/data, and then write to spreadsheet, but I haven't quite figured it out...
    Thanks,
    Daryn

    For the first, you could convert everything to strings, then send an array of strings. For the second, just send an array of numbers.
    Cameron
    To err is human, but to really foul it up requires a computer.
    The optimist believes we are in the best of all possible worlds - the pessimist fears this is true.
    Profanity is the one language all programmers know best.
    An expert is someone who has made all the possible mistakes.
    To learn something about LabVIEW at no extra cost, work the online LabVIEW tutorial(s):
    LabVIEW Unit 1 - Getting Started
    Learn to Use LabVIEW with MyDAQ

  • Best Way to Replicate Azure SQL Databases to Lower Environments

    I have XML files delivered to my server where they are parsed into reference data and written to a database (Premium tier).  I want to have that database sync to other databases (Basic tier) so that my non-production environments can use the same reference
    data.
    I tried Data Sync and it seems incredibly slow.  Is Azure Data Sync the best way?  What are my other options?  I don't really want to change my parser to write to 3 different databases each time they receive an updated XML file, but I suppose
    that is an option.

    Greg,
    Data sync is one of the option but I wouldn't recommend as Data-Sync Service is going to be deprecated in near future. I would urge you to go through the options around Geo-replication. There are 3 versions of Geo-repl and i believe Active-Geo replication
    would suit your requirement however the copy of the database which is in sync will also have to be in the same service tier (Basic is not possible). With the current Azure offering, it is not possible to have a sync copy of database with different SLOs. I
    would also recommend you to open a support incident with Microsoft to understand different options of Geo-replication. Throughout the time I was composing my answer, keeping DR (disaster recovery) in mind. If i am mistaken, please let me know.
    -Karthik Krishnamurthy (SQK Azure KKB)

  • What's the best way to write freehand with InDesign?

    I have a Wacom and want to place some handwriting on my document - what's the best way to do this?

    Try the pen or pencil tools or do it in Photoshop and place it.
    Bob

  • Best way to write entire DVD-R?

    It's come to my attention that certain set top DVD players (Phillips in particular) won't play recordable media with a small amount of information written to the disc. But if you burn more than 4GB to the disc, the player reads the disc just fine. I'm working with a 15-minute program, so I'm obviously not near the 4GB. I'm interested in maximizing functionality and playability on all machines, so I'm wondering if there's a way within DVDSP, Disk Utility or Toast to write the entire disc. I've tested this by inserting video tracks that the user cannot reach from the menus, but the user could easily use the 'chapter forward' function and get lost in the dummy tracks. Thanks in advance for any thoughts.

    Yes, TY media are good, but Memorex? This forum is littered with references to the coasters that they make.
    The media in question here are TY, Verbatim and some leftover Apple brand discs from the old days. DVD-R manufacturer definitely has nothing to do with this. It's definitely an idiosyncrasy of the Phillips player in question. I've never had it happen with any of the other dozen or so players we have around here.
    We maintain many different brands of DVD player in our studios to be able to simulate any situation our products may find themselves in. Our goal is to be able to reach the largest audience possible for our clients, no matter their technological limitations. That is not always easy or even possible, given the amount of old, poor, and poorly maintained computers and DVD players out there. But we try to reach as many as possible. As tempting as it might be to always blame the user's equipment, we have to try to find novel ways of making every project as accessible as possible.
    I'll mark this question as answered, because I've discovered that there is no way to write to the edge of a DVD-R without the requisite amount of QT tracks within the DVDSP project. If anyone ever has any other ideas, please offer them. Thanks to all for contributing.

  • Best way to write NotInFilter ?

    What's the best way to accomplish a NotInFilter? I want to accomplish something like:
    Filter includeThesePeople = new NotInFilter("getName", setOfExcludedPeople);Thanks,
    Andrew

    Hi Andrew
    Yes, you need to chain two filters together
    Set setResults = cache.entrySet(new NotFilter(
    new InFilter("getName", setOfExcludedPeople)));
    Thanks
    /Charlie

Maybe you are looking for