A better way to write this.

My hope was to run through the list of inks and check each ink to see if it matched with a name in my array and then assign a value. I was attempts were unsuccessful. So I went with a bunch of if statements. I know I should be able to reduce this down and say if variable ink ==name in this array assign it this value from this array.
When I make a second loop to get to the array name the first loop does not work.
I just need a point in the right direction.
myDocument=app.activeDocument;
densityChange();
function densityChange(){
/*for (i=0; i<myDocument.swatches.length; i++){
                name = myDocument.swatches[i].name;
              //neutralDensity
     alert(name);
var ssDensityChng=(["203 Mandarin","201 Orange","601 Purple","202 Met Orange","302 Yellow","401 Bright Grn","301 Golden Yel","106 Bright Red","104 Cadmium Red","102 Maroon","103 Dark Red","101 Burgundy","501 Met Blue","602 Met Purple","404 Met Sage","712 Bronze","704 Silver","702Met Pewter"]);
var myDensity=([0.0341,0.0699,0.1076,0.1473,0.1892,0.2337,0.281,0.3315,0.3858,0.4444,0.508,0. 5776,0.6545,0.7403,0.8375,0.9493,1.0813,1.242]);
for (i=0; i<myDocument.inks.length; i++){
                var name = myDocument.inks[i].name;
                var density = myDocument.inks[i].neutralDensity;
                if(name== "203 Mandarin"){
                density=myDocument.inks[i].neutralDensity=0.0341;
                if(name=="201 Orange"){
                density=myDocument.inks[i].neutralDensity=0.0699;
                if(name=="601 Purple"){
                density=myDocument.inks[i].neutralDensity=0.1076;
                if(name=="202 Met Orange"){
                density=myDocument.inks[i].neutralDensity=0.1473;
                if(name=="302 Yellow"){
                density=myDocument.inks[i].neutralDensity=0.1892;
                if(name=="401 Bright Grn"){
                density=myDocument.inks[i].neutralDensity=0.2337;
                if(name=="301 Golden Yel"){
                density=myDocument.inks[i].neutralDensity=0.281;
                if(name=="106 Bright Red"){
                density=myDocument.inks[i].neutralDensity=0.3315;
                if(name=="104 Cadmium Red"){
                density=myDocument.inks[i].neutralDensity=0.3858;
                if(name=="102 Maroon"){
                density=myDocument.inks[i].neutralDensity=0.4444;
                if(name=="103 Dark Red"){
                density=myDocument.inks[i].neutralDensity=0.508;
                if(name=="101 Burgundy"){
                density=myDocument.inks[i].neutralDensity=0.5776;
                if(name=="501 Met Blue"){
                density=myDocument.inks[i].neutralDensity=0.6545;
                if(name=="602 Met Purple"){
                density=myDocument.inks[i].neutralDensity=0.7403;
                if(name=="404 Met Sage"){
                density=myDocument.inks[i].neutralDensity=0.8375;
                if(name=="712 Bronze"){
                density=myDocument.inks[i].neutralDensity=0.9493;
                if(name=="704 Silver"){
                density=myDocument.inks[i].neutralDensity=1.0813
                if(name=="702Met Pewter"){
                density=myDocument.inks[i].neutralDensity=1.242;

Sorry I didn't provide much in the way of explanation with the code. The links Jongware provided should help you understand what's happening in the loop.
i and l are variable declarations. They aren't defined until the for statement. It's considered good style in certain precincts to only have one var declaration statement per function or program, which makes explicit how JavaScript will treat them—by hoisting them to the top, that is. This is to help you not make some incorrect but perfectly natural assumptions about the scope of your variables. Douglas Crockford and his JSLint are the driving forces behind this convention.
The l in my loop is probably confusing. I'm simply caching the length of the doc.inks collection so I don't have to check it on every go-round. This can make a surprising performance difference in large loops but is totally unnecessary here. (But that's the way I have it set up in Text Expander, so that's how it comes out!)
The if statement is checking whether the name of the current ink is one of the keys in the densities object/dictionary/hash/associative array. If it is, then the ink's neutralDensity is assigned the value of that key. So if the ink's name is "203 Mandarin", its neutralDensity will be assigned the value of densities["203 Mandarin"], which is 0.0341. I think I'm not explaining very well; probably stepping through it in the ESTK and looking at your values in the console will be more enlightening.
Jeff

Similar Messages

  • Looking for a better way to write this SQL

    Oracle version 11R2
    OS version (does not matter)
    What I trying to do is write a query that finds Public Synonyms without a target object. I came up with this but I thinking there's a better way.
    Select
      s.owner, s.synonym_name, s.table_name, s.table_owner, s.db_link, InitCap(o.object_type) object_type
    from  
      sys.DBA_SYNONYMS s, sys.DBA_OBJECTS o
    where 
      s.synonym_name is not null
    and   
      s.table_owner = o.owner (+)
    and   
      s.table_name = o.object_name (+)
    and   
      s.owner = 'PUBLIC'
    and
      object_type is null;  object_type is null appears to be the weakness. It seems the check of the target object should be better.
    Feedback, comments, queries welcome.

    I'm not sure exactly what "better" means in this context (faster, easier to read, etc.) but I'd tend to use a NOT EXISTS
    SELECT s.*
      FROM dba_synonyms s
    WHERE owner = 'PUBLIC'
       AND s.db_link IS NULL
       AND NOT EXISTS (
        SELECT 1
          FROM dba_objects o
         WHERE o.owner = s.table_owner
           AND o.object_name = s.table_name )I added the DB_LINK criteria to filter out public synonyms that reference objects in remote databases which obviously don't exist in the local DBA_OBJECTS.
    Justin

  • A better way to write this in pl\sql

    I have a query with the following condition:
    WHERE a.sortest_tesc_code in ('EB','MB','CH','CL','EP','FL','FR','GL', 'GM','IT','JL','KL','LR','LT','MI','M2', 'IC','2C','MH','PH','SL','SP','UH','WH','WR')
    I am using a subquery to retrieve the maximum score:
    It is possible to have a student that take up to 6 test (out of those codes) or more.
    I have to store the maximum score in a column top1, then top2, top 3
    For example:
    APPLICANT_PIDM     SORTEST_TESC_CODE     SORTEST_TEST_SCORE
    69136     CH     660
    69136     FR     680
    69136     WR     600
    FR 680 will go to TOP1 and CH 660 will go to top2 and WR 600 TOP 3.
    I DON’T want to create 25 variables to do the compare, is there an easy way to do this in PL\SQL, I AM THINKING IN using records, but I am not sure I can do it that way, so I am asking you? Can you give me some ideas, AGAIN, I don’t want to create all those variables.. ANY IDEAS will be appreciated.

    If you have all the eligible scores in the inner_query, then
    select * FROM (
    select applicant_pidm, sorttest_tesc_code,sorttest_test_score,
    select row_number() OVER (PARTITION BY applicant_pidm ORDER BY sorttest_test_score DESC) ranking
    WHERE ranking <= 3
    will give you the raw information you need, then you can use CASE or DECODE to "pivot",
    i.e.
    select topcode1....
    FROM
    (select CASE WHEN ranking = 1 THEN sorttest_tesc_code ELSE NULL END TopCode1....
    GROUP BY applicant_pidm
    Jon

  • Need help to get alternate or better way to write query

    Hi,
    I am on Oracle 11.2
    DDL and sample data
    create table tab1 -- 1 millions rows at any given time
    id       number       not null,
    ref_cd   varchar2(64) not null,
    key      varchar2(44) not null,
    ctrl_flg varchar2(1),
    ins_date date
    create table tab2 -- close to 100 million rows
    id       number       not null,
    ref_cd   varchar2(64) not null,
    key      varchar2(44) not null,
    ctrl_flg varchar2(1),
    ins_date date,
    upd_date date
    insert into tab1 values (1,'ABCDEFG', 'XYZ','Y',sysdate);
    insert into tab1 values (2,'XYZABC', 'DEF','Y',sysdate);
    insert into tab1 values (3,'PORSTUVW', 'ABC','Y',sysdate);
    insert into tab2 values (1,'ABCDEFG', 'WYZ','Y',sysdate);
    insert into tab2 values (2,'tbVCCmphEbOEUWbxRKczvsgmzjhROXOwNkkdxWiPqDgPXtJhVl', 'ABLIOWNdj','Y',sysdate);
    insert into tab2 values (3,'tbBCFkphEbOEUWbxATczvsgmzjhRQWOwNkkdxWiPqDgPXtJhVl', 'MQLIOWNdj','Y',sysdate);I need to get all rows from tab1 that does not match tab2 and any row from tab1 that matches ref_cd in tab2 but key is different.
    Expected Query output
    'ABCDEFG',  'WYZ'
    'XYZABC',   'DEF'
    'PORSTUVW', 'ABC'Existing Query
    select
       ref_cd,
       key
    from
        select
            ref_cd,
            key
        from
            tab1, tab2
        where
            tab1.ref_cd = tab2.ref_cd and
            tab1.key    <> tab2.key
        union
        select
            ref_cd,
            key
        from
            tab1
        where
            not exists
               select 1
               from
                   tab2
               where
                   tab2.ref_cd = tab1.ref_cd
        );I am sure there will be an alternate way to write this query in better way. Appreciate if any of you gurus suggest alternative solution.
    Thanks in advance.

    Hi,
    user572194 wrote:
    ... DDL and sample data ...
    create table tab2 -- close to 100 million rows
    id       number       not null,
    ref_cd   varchar2(64) not null,
    key      varchar2(44) not null,
    ctrl_flg varchar2(1),
    ins_date date,
    upd_date date
    insert into tab2 values (1,'ABCDEFG', 'WYZ','Y',sysdate);
    insert into tab2 values (2,'tbVCCmphEbOEUWbxRKczvsgmzjhROXOwNkkdxWiPqDgPXtJhVl', 'ABLIOWNdj','Y',sysdate);
    insert into tab2 values (3,'tbBCFkphEbOEUWbxATczvsgmzjhRQWOwNkkdxWiPqDgPXtJhVl', 'MQLIOWNdj','Y',sysdate);
    Thanks for posting the CREATE TABLE and INSERT statments. Remember why you go to all that trouble: so the people whop want to help you can re-create the problem and test their ideas. When you post statemets that don't work, it's just a waste of time.
    None of the INSERT statements for tab2 work. Tab2 has 6 columns, but the INSERT statements only have 5 values.
    Please test your code before you post it.
    I need to get all rows from tab1 that does not match tab2 WHat does "match" mean in this case? Does it mean that tab1.ref_cd = tab2.ref_cd?
    and any row from tab1 that matches ref_cd in tab2 but key is different.
    Existing Query
    select
    ref_cd,
    key
    from
    select
    ref_cd,
    key
    from
    tab1, tab2
    where
    tab1.ref_cd = tab2.ref_cd and
    tab1.key    <> tab2.key
    union
    select
    ref_cd,
    key
    from
    tab1
    where
    not exists
    select 1
    from
    tab2
    where
    tab2.ref_cd = tab1.ref_cd
    Does that really work? In the first branch of the UNION, you're referencing a column called key, but both tables involved have columns called key. I would expect that to cause an error.
    Please test your code before you post it.
    Right before UNION, did you mean
    tab1.key    != tab2.key? As you may have noticed, this site doesn't like to display the &lt;&gt; inequality operator. Always use the other (equivalent) inequality operator, !=, when posting here.
    I am sure there will be an alternate way to write this query in better way. Appreciate if any of you gurus suggest alternative solution.Avoid UNION; it can be very inefficient.
    Maybe you want something like this:
    SELECT       tab1.ref_cd
    ,       tab1.key
    FROM           tab1
    LEFT OUTER JOIN  tab2  ON  tab2.ref_cd     = tab1.ref_cd
    WHERE       tab2.ref_cd  IS NULL
    OR       tab2.key     != tab1.key
    ;

  • A better way to write last_day query

    Hi folks,
    I am looking for a better way to write a query to find last_day in month but if its sunday or holiday it should move to day before last day.
    So for example if 31 is sunday it should go for 30, if 30 is holiday it should move down to 29.
    I got this so far but the connect by level is hardcoded to 15. Want to see if there is a better way to get this working:
    select max(datum)
      from (    select last_day(trunc(sysdate)) - level + 1 as datum
                  from dual
            connect by level < 15)
    where to_char(datum, 'day') != 'sunday'    
       and to_char(datum, 'DDMM') not in
             ('3012')Best regards,
    Igor

    Like this
    select to_char(last_day_month, 'Day') day_is,
           last_day_month,
           last_day_month - case when to_char(last_day_month, 'fmday') = 'sunday' then 1
                                 when to_char(last_day_month, 'ddmm' ) = '3012'   then 1
                                 else 0
                            end last_business_day_month
      from (
              select last_day(add_months(trunc(sysdate, 'year'), level-1)) last_day_month
                from dual
              connect by level <= 12
    DAY_IS    LAST_DAY_MONTH LAST_BUSINESS_DAY_MONTH
    Tuesday   31-JAN-12      31-JAN-12              
    Wednesday 29-FEB-12      29-FEB-12              
    Saturday  31-MAR-12      31-MAR-12              
    Monday    30-APR-12      30-APR-12              
    Thursday  31-MAY-12      31-MAY-12              
    Saturday  30-JUN-12      30-JUN-12              
    Tuesday   31-JUL-12      31-JUL-12              
    Friday    31-AUG-12      31-AUG-12              
    Sunday    30-SEP-12      29-SEP-12              
    Wednesday 31-OCT-12      31-OCT-12              
    Friday    30-NOV-12      30-NOV-12              
    Monday    31-DEC-12      31-DEC-12 

  • I am having trouble transferring files from an old MacBook (2007) to a MacBook Air over a wireless network.  The connection was interrupted and the time was over 24 hours.  Is there a better way to do this?  I'm using Migration assistant.

    I am having trouble transferring files from an old MacBook (2007) to a MacBook Air over a wireless network.  The connection was interrupted and the time was over 24 hours.  Is there a better way to do this?  I'm using Migration assistant.  The lack of an ethernet port on MacBook air does not help.

    William ..
    Alternative data transfer methods suggested here > OS X: How to migrate data from another Mac using Mavericks

  • There's got to be a better way to do this (RAM preview frustration)

    I loaded a 1:20 second Full HD clip into after effects. I need to edit the video based on certain sounds in the video and see if I'm matching them up correctly by previewing it with sound.
    The problem is i'm getting frustrated due to After effects not behaving like Premiere. First who thought it was a good idea not to incorporate sound into after effects? Second, I have an i7 sandy bridge processor, and 16 gbs of ram, yet it still takes time to render the ram preview (with no effects on it yet).
    So ram preview is my only option for sound, but the problem is every time I hit ram preview it starts the video all the way from the beginning. This is frustrating as I want to start at a specific point. Imagine having a longer video where the editing needs to take place at the end.
    There are people out there doing a lot more complicated professional projects, what do you guys do to get around this?
    Why can't after effects do some basic things like premiere like render fast with sound? Is it due to Mercury engine and 64 bits?
    This is one of the best products on the market, surely there is a better way to do this right?

    but the problem is every time I hit ram preview it starts the video all the way from the beginning.
    Window --> Preview, enable the "From current time" option
    yet it still takes time to render the ram preview (with no effects on it yet).
    There is no magic button. If it is compressed, naturally it needs to be decompressed and decoded first. This can consume resources even on fast machines. Furthermore, drive speed matters a lot in such cases. This might actualyl multiply, if you use multiprocessing, so for this kind of simple setup it's usually better to not use it. If your harddrives are fragmented or simply generally slow, frames cannot be loaded as fast and neither will AE be able to use the disk cache. Ergo, convert the footage and move it to the fastest drive in your system.
    what do you guys do to get around this?
    We preview at reduced compo resolution to extend RAM previews and place markers while the RAM preview plays using the * key on the numpad.
    Mylenium

  • Better Way To Do This? Selector Operator...

    I'm currently writing the selection operator for the algorithm. The aim of it is
    to rate how the coursework block have been allocated and give there allocation
    a rating...
    How I have done it is have a method that searches through the one of the parent
    timetables. It looks for coursework time blocks. Once it finds one it notes
    this and looks at the next block along. If this is a coursework time block it
    notes this as well. I then perform an operation comparing these two coursework
    time blocks to find out if they are for the same Module. If they are not this
    is not a very effective coursework timetable strategy.
    Because of this I note in an array the the position of these two coursework time
    block and give them a fitness rating of 1000. I then go on to see if the next
    block is a coursework time block. If it is and its not of the same Module ID of
    the two previous then I not these 3 block down in an array and give them a
    fitness rating of 2000.
    My concern is that I am using allot of if and for loop's and the code is
    starting to look untidy at best. Is there any better way of doing this?
    Below Is my code:
          * @param parentOne
          * @param parentTwo
         public void selectionOperator(ArrayList parentOne, ArrayList parentTwo){
              // Store's the fitness rating of sections of the timetable...          
              ArrayList parentOneBlockFitnessRating = new ArrayList ();
              ArrayList parentTwoBlockFitnessRating = new ArrayList ();
              //Loops through the timetable's timeblocks...
              for (int i = 0; i < parentOne.size(); i++) {
                   //Checks to see if the current time block is of the class: CourseworkTimeBlock,
                   //if so it enters this statement...
                   if(parentOne.get(i).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                        //A temp store for the current CourseworkTimeBlock...
                        CourseworkTimeBlock tempBlockOne = (CourseworkTimeBlock) parentOne.get(i);
                        System.out.println("Got Here!, Module ID...: " + tempBlockOne.getModuleId());
                        //Checks to see if the next time block along is of the class: CourseworkTimeBlock,
                        //if so it enters this statement...
                        if(parentOne.get(i+1).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                             //A temp store for the next CourseworkTimeBlock...
                             CourseworkTimeBlock tempBlockTwo = (CourseworkTimeBlock) parentOne.get(i+1);
                             System.out.println("Got Here Aswell!");
                             //Checks to see if the current and next CourseworkTimeBlock module Id's
                             //are the same, if there arn't then this section is entered...
                             if(!tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId())){
                                  //Checks to see if the second time block along is of the class: CourseworkTimeBlock,
                                  //if so it enters this statement...
                                  if(parentTwo.get(i+2).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                                       //A temp store for the second CourseworkTimeBlock along...
                                       CourseworkTimeBlock tempBlockThree = (CourseworkTimeBlock) parentTwo.get(i+2);
                                       //Checks to see if all 3 of the Module Id's of the CourseworkTimeBlocks match,
                                       //if they don't match this statement is entered...
                                       if(! tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId()) && (tempBlockTwo.getModuleId().equals(tempBlockThree.getModuleId()))) {
                                            //ArrayList to store the fitness rating of the current block
                                            //selection...
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(i);
                                            //Position of second block.
                                            blockFitness.add(i+1);
                                            //Position of second block.
                                            blockFitness.add(i+2);
                                            //Fitness Value
                                            blockFitness.add(2000);
                                            //Add block rating to main rating ArrayList...
                                            parentOneBlockFitnessRating.add(blockFitness);
                                       else{
                                            //ArrayList to store the fitness rating of the current block
                                            //selection...
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(i);
                                            //Position of second block.
                                            blockFitness.add(i+1);
                                            //Fitness Value
                                            blockFitness.add(1000);
                                            //Add block rating to main rating ArrayList...
                                            parentOneBlockFitnessRating.add(blockFitness);
              for (int o = 0; o < parentTwo.size(); o++) {
                   if(parentTwo.get(o).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                        CourseworkTimeBlock tempBlockOne = (CourseworkTimeBlock) parentTwo.get(o);
                        System.out.println("Got Here!, Module ID...: " + tempBlockOne.getModuleId());
                        if(parentTwo.get(o+1).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                             CourseworkTimeBlock tempBlockTwo = (CourseworkTimeBlock) parentTwo.get(o+1);
                             System.out.println("Got Here Aswell!");
                             if(!tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId())){
                                  if(parentTwo.get(o+2).getClass().toString().equals("class Timetable.CourseworkTimeBlock")){
                                       CourseworkTimeBlock tempBlockThree = (CourseworkTimeBlock) parentTwo.get(o+2);
                                       if(! tempBlockOne.getModuleId().equals(tempBlockTwo.getModuleId()) && (tempBlockTwo.getModuleId().equals(tempBlockThree.getModuleId()))) {
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(o);
                                            //Position of second block.
                                            blockFitness.add(o+1);
                                            //Position of second block.
                                            blockFitness.add(o+2);
                                            //Fitness Value
                                            blockFitness.add(2000);
                                            //Add block rating to main rating ArrayList...
                                            parentTwoBlockFitnessRating.add(blockFitness);
                                       else{
                                            ArrayList <Integer> blockFitness = new ArrayList<Integer>();
                                            //Position of first block.
                                            blockFitness.add(o);
                                            //Position of second block.
                                            blockFitness.add(o+1);
                                            //Fitness Value
                                            blockFitness.add(1000);
                                            //Add block rating to main rating ArrayList...
                                            parentTwoBlockFitnessRating.add(blockFitness);
         }As you can see there are allot if statements and some bad coding practice to boot. But I don't know what other ways to do it....
    Any directions of other ways how to do this?
    Many Thanks
    Chris

    Unfortunately, I think you're stuck with a bunch of if-statements.
    Fortunately, I have some things that may help you.
    First, I usually make sure something is of x class via this
    if (someObject instanceof SomeClass) {So, I'd adjust your 'class checking' conditionals from this
    if(parentOne.get(i).getClass().toString().equals("class Timetable.CourseworkTimeBlock"))to this
    if (parentOne.get(i) instanceof Timetable.CourseworkTimeBlock) {Secondly, your code logic is kind of confusing.
    Why do you have a for-loop that iterates through every CourseworkTimeBlock, if you then (within each possible iteration) check iteration+1 and iteration+2? What happens if those throw an ArrayIndexOutOfBoundsException, or are null?

  • Better Way to do this loop.

    I know there is better ways to do this so that I can merely have it loop infinitely until it hits the max password. I would also like to keep the spot where it has the print Statements because I tend to set some other code in front of it.
    If anyone also has some Ideas so I can have it stop and start in particular positions.
    Like lets say ?!!!!? to ?~~~~?
    Thanks a ton. Below is the code.
       char[] password = new char[20];
       int current_last_letter = 0;
       int max_password = 3;
       while(current_last_letter < max_password)
       for(int counter_gamma = 32; counter_gamma <= 126; counter_gamma++)
           for(int counter_beta = 32; counter_beta <= 126; counter_beta++)
                for(int counter_alpha = 32; counter_alpha <= 126; counter_alpha++) //alpha = increase last character by one
                    password[current_last_letter] = (char)counter_alpha;
                    System.out.print(password);
                    System.out.println("::null");
                if(current_last_letter > 0)
                    password[current_last_letter-1] = (char)counter_beta;
                else
                    counter_beta = 127;
            if(current_last_letter > 1)
                password[current_last_letter-2] = (char)counter_gamma;
            else
                counter_gamma = 127;
       current_last_letter++;
                   

    If I interpreted your code right, you simply want to count in radix '~'-' '+1 (read this carefully).
    Given a password, and a lo/hi value for the character range, the following method returns the
    lexicographically next password. The method returns null if no such password exists --    char[] nextPassword(char[] pw, char lo, char hi) {
          for (int i= pw.lenght; --i >= 0;)
             if (pw[i] < hi) { // next character possible here?
                pw[i]++;
                return pw;
             else // * no, reset to first value and continue;
                pw= lo;
    return null; // all pw-chars reached their hi value
    So, if you initialize a password char array as follows --    char[] pw= new char[20];
       Arrays.fill(pw, ' '); the following fragment handles every possible password --    do {
          handlePassword(pw); // do something with pw
          pw= nextPassword(pw, ' ', '~');
       } while (pw != null); kind regards,
    Jos

  • Is there better way to write SQl Insert Script

    I am running out of ideas while working on one scenario and thought you guys would be able to guide me in right way.
    So, the scenario is I have a Table table1 table1(fieldkey, DisplayName, type) fieldkey - pkey   This table have n number of rows. The value of fieldkey in nth row is n. So if we have 1000 record, then the last row has a fieldkey = 1000.
    Below is my sample data.
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1001, 'COfficer',100);
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1002, 'PData',100);
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1003, 'EDate',100);
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1004, 'PData',200);
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1005, 'EDate',300);
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    (1006, 'Owner',400);This way of inserting the row with hardcoded value of fieldkey was creating the problem when the same table was used by other developer for their own new functionality.
    So, I thought of using the max(fieldkey) +1 from that table and use it in my insert script. This script file runs every time during software installation.
    I thought of using count to see if the row with same displaytype and type exists in that table or not. If exisits do not insert new row, if not insert new row.
    It looks like i will have to query the count statement everytime before I insert the row.
    select max(fieldkey) +1 into ll_fieldkey from table1
    select count(*) into ll_count from table1 where display ltrim(upper(name)) = 'COFFICER' and type =100)
    if ll_count >0 then
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    ( ll_fieldkey, 'COfficer',100);
    ll_fieldkey := ll_fieldkey +1
    end if;
    select count(*) into ll_count from table1 where display ltrim(upper(name)) = 'PData' and type =100)
    if ll_count >0 then
    Insert into table1 (FIELDKEY,DISPLAYNAME,TYPE) values
    ( ll_fieldkey, 'PData',100);
    ll_fieldkey := ll_fieldkey +1
    end if;
    ... and so on for all the insert statement. So, i was wondering if there is some better way to handle this situation of inserting the data.
    Thank you

    Hi !
    For check if the same display name and type already exists in table i would use Unique Key , but then again instead of if statement you should code some exception handlers. ... Hm .. Unque key is by may opinion better solution as
    codeing checks .
    For faster inserts that is , smaller code .. if there is no rules for values and the values are fixed , in any case you have to do this 100 inserts. If you can "calculate" values then maybe you can figure out some code .. but effect will be the same as hundred insert stetements one after another .. Procedure with this 100 inserts is not so bad solution.
    You can fill with values a nested table and then use forall ... save exceptions insert and with above mentioned UK , maybe this will be better.
    T
    Edited by: ttt on 10.3.2010 13:01

  • Better way to do this

    When selecting into a variable, is there a better way to do this? I want to make sure I don't get an error if there are no rows found. I think it's inefficient to count the number of occurrences before selecting into the variable. Can I use %NOROWSFOUND or something similar? If so, can you please provide an example? Thanks, Margaret
    Tzi := null;
    SELECT count(BUSINESS_tz)
    INTO Tzi_cnt
    FROM BUSINESS O
    WHERE ID = Fac_id AND BUSINESS_type = 'Store' AND O.Business_seq = (SELECT Business_seq
    FROM Org_lookup
    WHERE Store_seq = 0);
    IF Tzi_cnt > 0
    THEN
    SELECT BUSINESS_tz
    INTO Tzi
    FROM BUSINESS O
    WHERE ID = Fac_id AND BUSINESS_type = 'Store' AND O.Business_seq = (SELECT Business_seq

    the proper way to do this is to use an exception block;
    so
    begin
    Tzi := null;
    SELECT BUSINESS_tz
    INTO Tzi_cnt
    FROM BUSINESS O
    WHERE ID = Fac_id AND BUSINESS_type = 'Store' AND O.Business_seq = (SELECT Business_seq
    FROM Org_lookup
    WHERE Store_seq = 0);
    exception
    when no_data_found
    then
       null;   -- put any code to execute here or raise exception
    end;you can also use sql%rowcount to find out how many rows your sql statement affected:
    eg directly after your sql and before any rollback or commit
    declare
    v_rowcount number;
    begin
    insert into <table_name>
    select * from <other_table>;
    v_rowcount := sql%rowcount;
    end;

  • How to create a function with dynamic sql or any better way to achieve this?

            Hello,
            I have created below SQL query which works fine however when scalar function created ,it
            throws an error "Only functions and extended stored procedures can be executed from within a
            function.". In below code First cursor reads all client database names and second cursor
            reads client locations.
                      DECLARE @clientLocation nvarchar(100),@locationClientPath nvarchar(Max);
                      DECLARE @ItemID int;
                      SET @locationClientPath = char(0);
                      SET @ItemID = 67480;
       --building dynamic sql to replace database name at runtime
             DECLARE @strSQL nvarchar(Max);
             DECLARE @DatabaseName nvarchar(100);
             DECLARE @localClientPath nvarchar(MAX) ;
                      Declare databaselist_cursor Cursor for select [DBName] from [DataBase].[dbo].
                      [tblOrganization] 
                      OPEN databaselist_cursor
                      FETCH NEXT FROM databaselist_cursor INTO @DatabaseName
                      WHILE @@FETCH_STATUS = 0
                      BEGIN       
       PRINT 'Processing DATABASE: ' + @DatabaseName;
        SET @strSQL = 'DECLARE organizationlist_cursor CURSOR
        FOR SELECT '+ @DatabaseName +'.[dbo].[usGetLocationPathByRID]
                                   ([LocationRID]) 
        FROM '+ @DatabaseName +'.[dbo].[tblItemLocationDetailOrg] where
                                   ItemId = '+ cast(@ItemID as nvarchar(20))  ;
         EXEC sp_executesql @strSQL;
        -- Open the cursor
        OPEN organizationlist_cursor
        SET @localClientPath = '';
        -- go through each Location path and return the 
         FETCH NEXT FROM organizationlist_cursor into @clientLocation
         WHILE @@FETCH_STATUS = 0
          BEGIN
           SELECT @localClientPath =  @clientLocation; 
           SELECT @locationClientPath =
    @locationClientPath + @clientLocation + ','
           FETCH NEXT FROM organizationlist_cursor INTO
    @clientLocation
          END
           PRINT 'current databse client location'+  @localClientPath;
         -- Close the Cursor
         CLOSE organizationlist_cursor;
         DEALLOCATE organizationlist_cursor;
         FETCH NEXT FROM databaselist_cursor INTO @DatabaseName
                    END
                    CLOSE databaselist_cursor;
                    DEALLOCATE databaselist_cursor;
                    -- Trim the last comma from the string
                   SELECT @locationClientPath = SUBSTRING(@locationClientPath,1,LEN(@locationClientPath)-  1);
                     PRINT @locationClientPath;
            I would like to create above query in function so that return value would be used in 
            another query select statement and I am using SQL 2005.
            I would like to know if there is a way to make this work as a function or any better way
            to  achieve this?
            Thanks,

    This very simple: We cannot use dynamic SQL from used-defined functions written in T-SQL. This is because you are not permitted do anything in a UDF that could change the database state (as the UDF may be invoked as part of a query). Since you can
    do anything from dynamic SQL, including updates, it is obvious why dynamic SQL is not permitted as per the microsoft..
    In SQL 2005 and later, we could implement your function as a CLR function. Recall that all data access from the CLR is dynamic SQL. (here you are safe-guarded, so that if you perform an update operation from your function, you will get caught.) A word of warning
    though: data access from scalar UDFs can often give performance problems and its not recommended too..
    Raju Rasagounder Sr MSSQL DBA
          Hi Raju,
           Can you help me writing CLR for my above function? I am newbie to SQL CLR programming.
           Thanks in advance!
           Satya
              

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

  • Is there another easy way to write this program??

    Hi ,i new in Java Programing,Is there another way to write this program?? This program below is about FIND THE AREA OF A CIRCLE WHEREIN THE RADIUS OF THE CIRCLE RANGES FROM 1 TO 10 BY 1 IN A FOR LOOP.
    import javax.swing.JOptionsPane;
    public class Area2 {
    public static void main(String[] args ) {
    double pi = 3.14;
    int r;
    String a = "Area = ";
    double area;
    for (r = 1; <= 10; r++)
    area = pi * r * r;
    a = a + area + "\n";
    JOptionPane.showMessageDialog(
    null , a);
    System.exit ( 0 );
    I did not write it ,i want to know if is there another way (easy)to write it.
    Thank you very much
    Sincerely Erick.

    Not much to improve upon this. It is a pretty simple program. Note my comment about PI.
    import javax.swing.JOptionsPane;
    public class Area2 {
       public static void main(String[] args ) {
          double final PI = 3.14; // Final because it's a constant value, convention for constants is to use uppercase
         int r;
         String a = "Area = ";
        for  (r = 1; <= 10; r++)
            area  = pi * r * r;
            a = a + area +  "\n";
        JOptionPane.showMessageDialog(null , a);
        System.exit  ( 0 );

  • Callouts and anchored objects - there must be a better way to do this

    I've spent a lot of time in the last six months rebuilding PDF files in InDesign. It's part of my ordinary responsibilities, but I'm doing a lot more of it for some reason. Because I'm sending the text of these rebuild documents out for translation, I like to keep all of the text in a single story. It really helps to have the text in "logical order," I think; when I'm prepping a trifold brochure, I try pretty hard to make sure that the order in which the readers will read the text is duplicated in the flow of the story throughout the ID document.
    So, I'm rebuilding a manual that has a 3-column format on lettersize paper, and it's full of callouts. Chock full of 'em. They're not pull quotes, either; each of these things has unique text. Keeping in mind that I'd like the text in these callouts to remain in the same position in the text once I've linked all the stories and exported an RTF for translation, what's the best way to handle them? What I've been doing is inserting an emptly stroked frame as an anchored object, sized and positioned to sit above the text that is supposed to be called out. When my translations come back, they're always longer than the source document, so as I crawl through the text, I resize the anchored frames to match the size and position of the newly expanded translated text, and then nudge them into place with the keyboard.
    There Has To Be a Better Way.
    There is a better way, right? I'm not actually too sure. If I want to actually fill those anchored frames with text, I can't thread them into the story. I suppose that I could just thread the callout frames and assign two RTFs for translation instead of one, but then the "logical order" of my text is thrown out the window. So, I'm down to asking myself "what's more important? reduction of formatting time or maintenance of the flow of the story?" If there's something I'm missing that would let me dodge this decision, I'd love to hear about it. The only thing I can think of would work like this:
    1) Duplicate callout text in the story with a custom swatch "Invisible"
    2) Create "CalloutText" parastyle with "Invisible" swatch and apply it to callout text
    3) Insert anchor for anchored frame immediately before the CalloutText content
    4) Send it out for translation
    5) While I'm waiting for it to come back, write a script that would (dunno if this is possible):
       a) Step through the main story looking for any instance of CalloutText
       b) Copy one continguous instance of that style to the clipboard
       c) Look back in the story for the first anchor preceeding the instance of CalloutText
       d) Fill the anchored object with the text from the clipboard (this is where I'm really clueless)
       e) Apply a new parastyle to the text in the callout
       f) Continue stepping through the story looking for further instances of CalloutText
    If this really is the only decent solution, I'll just head over to the Scripting forum for some help with d). Can any of you make other suggestions?

    In-Tools.com wrote:
    The use of Side Heads saves weeks of manual labor.
    Yup, Harbs, that is exactly what I was describing. If I use the Side Heads plugin to set up a job, will my clients get a missing plug-in warning when they open up the INDD? Will roundtripping through INX strip the plugin but leave the text in the callout? (My clients don't care if the logical flow of the story is broken; it's just me.)
    I'm just curious; seems like a pretty obvious purchase to me. I'll probably try to script a solution anyways, after I buy the plugin; that way I get to learn about handling anchored objects in scripts AND deliver the job on time!

Maybe you are looking for