PL/SQL update rate using having count

Hi am newbie at pl/sql
I need to update rate_per_hour for all projects having less than 5 employee to 500
here is the code what i wrote, but it updates all employee
set serveroutput on
declare
  cursor rate_cur is
  select * from project
  for update of rate_per_hour;
begin
  for rate_rec IN rate_cur
  loop
    update project
    set rate_per_hour=500
    where current of rate_cur;
  end loop;
end;Here is my tables:
CREATE TABLE employee(
empid number(5),
empname varchar(20),
address varchar(20),
no_of_dependents number(5),
deptno number(5),
CONSTRAINT EMPLOYEE_PKEY PRIMARY KEY(empid),
CONSTRAINT EMPLOYEE_FKEY FOREIGN KEY(deptno) REFERENCES department(deptno));
CREATE TABLE project(
projectno number(5),
location varchar(20),
incharge number(5),
rate_per_hour number(5),
CONSTRAINT PROJECT_PKEY PRIMARY KEY(projectno),
CONSTRAINT PROJECT_FKEY FOREIGN KEY(incharge) REFERENCES employee(empid));
CREATE TABLE assignment(
empid number(5),
projectid number(5),
hours number(5),
CONSTRAINT ASSIGNMENT_FKEY FOREIGN KEY(empid) REFERENCES employee(empid),
CONSTRAINT ASSIGNEMNT_FKEY2 FOREIGN KEY(projectid) REFERENCES project(projectno));please suggest a solution
Edited by: user12970368 on Dec 15, 2011 6:55 AM

here is test data
/*department table */
insert into department values(201,'ADMINISTRATION',10000,101);
insert into department values(202,'FINANCE',10000,102);
insert into department values(203,'ACCOUTING',10000,103);
insert into department values(204,'HR',10000,104);
insert into department values(205,'TESTING',10000,105);
/*employee table
insert into employee values(101,'Marlen', 'DXB1',5,201);
insert into employee values(102,'Oleg', 'DXB2',2,201);
insert into employee values(103,'Adil', 'SHJ1',1,202);
insert into employee values(104,'Sultan', 'AD1',0,202);
insert into employee values(105,'John', 'AD2',1,203);
insert into project values(001,'Dubai Marina',101,50);
insert into project values(002,'Bur Dubai',101,40);
insert into project values(003,'Palm Jumeirah',103,60);
insert into project values(004,'Media city',101,100);
insert into project values(005,'TECOM',101,30);
/*assignment table */
insert into assignment values(101,001,55);
insert into assignment values(101,004,128);
insert into assignment values(101,005,77);
insert into assignment values(102,002,27);
insert into assignment values(103,003,250);Edited by: user12970368 on Dec 15, 2011 6:54 AM

Similar Messages

  • PWM Update Rate using PXI 7334 & 6602 cards

    I have a NI 8176 controller and a PXI 7334 (FlexMotion) Motion Controller Card. I am using the PWM output to control an actuator and I would like to update the duty-cycle as frequently as possible.
    I have the card PWM frequency set to 32 kHz, but can only achieve 1.5 kHz update rate.
    The attached VI shows the code I'm using to write to the card.
    I also have a PXI 6602 card, I can achieve an update rate of 6.5 kHz with that, but I bought the 7334 card with the expectation of achieving a faster update rate.
    Any advice on how to improve the update rate of either card would be appreciated. Likewise, does anyone know another hardware set-up that would be a viable alternative?
    Many thanks,
    Brian
    Attachments:
    pwm_generation_with_7334_card_-_tick_method_of_speed_measurement.vi ‏50 KB
    PWM_Benchmark_V1.1.vi ‏112 KB

    Hi Amaury, thanks for the fp2 file, I’ve just moved site, got my lab back yesterday. (please watch the numbers 7344 and 7334 in the text below!)
    The FPGA2 firmware I had was Version 5.20.0001, MAX would not allow me to select the file 7344pwm.fp2, I got the message “This file is not valid for the Flexmotion board selected”.
    However, I went to C:\Program Files\National Instruments\Motion\FlexMotion\bin and deleted 7344.fp2
    I then renamed 7344pwm.fp2 to 7344.fp2 and copied it to the “bin” folder, then in MAX I selected new file to download, pointed to 7344.fp2 and successfully download the new firmware to my 7334 motion controller. Now in MAX the FPGA2 firmware version is 5.20.000f.
    Unfortunately I c
    an still only update the PWM duty-cycle on my 7334 at 3.6 kHz!
    Is this correct? do I need to update the file 7334.fp2 instead? or does the file 7344pwm.fp2 also work for the 7334 card?
    Also, is it possible to generate a PWM using the stepper motor output in open-loop mode? If so, do you have example code on how this is done?
    Thanks again for your help,
    Brian
    Regards
    Ray Farmer

  • Having count of 1

    I would like to count how many ID have only had 1 Enrolment by year:
    I am assuming you would have to use having count = 1 or something like that.
    So I have the following example below
    ID 1 has 2 enrolments so dont count
    ID 2 has only 1 enrolment so count
    ID 3 has 2 enrolments so dont count
    ID 4 has 1 enrolment so count
    ID 5 has 2 enrolments so dont count
    ID 6 has 1 so count
    ID 7 and 8 have one each so count.
    Thanks
    CREATE TABLE DAN_PRU
    (ID     VARCHAR2(8),
    UNIT    VARCHAR2(8),
    YEAR VARCHAR2(8))
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (1,'POP','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (1,'DOP','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (2,'KUIP','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (3,'DIP','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (3,'YUP','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (4,'SII','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (5,'DYY','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (5,'LIW','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (6,'DFG','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (7,'DWQ','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (8,'DFR','2013');GIVES:
    ID     UNIT     YEAR
    1     POP     2013
    1     DOP     2013
    2     KUIP     2013
    3     DIP     2013
    3     YUP     2013
    4     SII     2013
    5     DYY     2012
    5     LIW     2012
    6     DFG     2012
    7     DWQ     2011
    8     DFR     2011WANT
    ENROLMENTS     YEAR
    2            2013
    1            2012
    2            2011
    using oracle 10

    Hi,
    Interesting problem!
    Chloe_19 wrote:
    I would like to count how many ID have only had 1 Enrolment by year:
    I am assuming you would have to use having count = 1 or something like that.That's an obvious first step. What makes this such an interesting problem is how you get from there to the final answer.
    What is the final answer? Do you want just one row, containing just one number (5 in this case, since there are 5 ids (2, 4, 6, 7 and 8) that have only 1 enrollment?
    So I have the following example below
    ID 1 has 2 enrolments so dont count
    ID 2 has only 1 enrolment so count
    ID 3 has 2 enrolments so dont count
    ID 4 has 1 enrolment so count
    ID 5 has 2 enrolments so dont count
    ID 6 has 1 so count
    ID 7 and 8 have one each so count.
    Thanks
    CREATE TABLE DAN_PRU
    (ID     VARCHAR2(8),
    UNIT    VARCHAR2(8),
    YEAR VARCHAR2(8)) Why is year a VARCHAR2? Why is it 8 characters long?
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (1,'POP','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (1,'DOP','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (2,'KUIP','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (3,'DIP','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (3,'YUP','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (4,'SII','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (5,'DYY','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (5,'LIW','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (6,'DFG','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (7,'DWQ','2013');
    INSERT INTO DAN_PRU (ID, UNIT, YEAR) VALUES (8,'DFR','2013');
    GIVES:How does the data above give the results below.
    For example, it looks like '2013' is the only year in the data. How do you get '2011' and '2012' in the results?
    Can the same id have multiple years? What results would you want in that case?
    ID     UNIT     YEAR
    1     POP     2013
    1     DOP     2013
    2     KUIP     2013
    3     DIP     2013
    3     YUP     2013
    4     SII     2013
    5     DYY     2012
    5     LIW     2012
    6     DFG     2012
    7     DWQ     2011
    8     DFR     2011WANTAre you saying the results below are what you want?
    ENROLMENTS     YEAR
    2            2013
    1            2012
    2            2011
    using oracle 10Can you get a result set that contains one row per id? (Or for each id/year combination; it's unclar what you want.)
    Can you restrict that result set to contain only the ids with only 1 enrollment?
    If you had a table like the previous result set, how would you solve the problem? Remember, any result set can be treated like a table, using a WITH clause.

  • Can I write merge SQL statement having count(*)?

    Hi this is a followup question of my previous post. I tried to use a merge SQL statement to solve my problem but now I bump into another problem.
    Now I have a table where the field I need to update is a partial PK
    when using a merge SQL statement, I have to put a where clause that check if count(*) = 1 because of the PK constraint
    Where can I put the count(*) = 1 clause?
    Here are the details:
    I have two tables TA and TB, where TA contains the fields ID, FULLNAME, TYPE and TB contains the fields ID, FIRSTNAME
    I want to update the firstnames in TB to be the firstnames from TA where TB.ID = TA.ID and TA.TYPE = 'ABC'
    {ID, FIRSTNAME} are PKs but for the same ID, there can be more than 1 firstname.
    e.g.
    TA
    ID | FULLNAME | TYPE
    1 Caroline T ABC
    2 Mary C DEF
    3 Peter J ABC
    TB
    ID | FIRSTNAME
    1 Caroline
    1 Carol
    1 C,
    3 Peter
    I need to update TB with the new firstnames from TA where type is 'ABC' but only for those fields that have count(TB.ID) = 1
    when I try to run this SQL statement
    merge into TB B using TA A
    on (A.ID = B.ID and A.TYPE = 'ABC')
    when matched then update set B.FIRSTNAME = substr(A.FULLNAME, 1, instr(A.FULLNAME, ',') - 1)
    I got this error SQL Error: ORA-00001: unique constraint (TEST.PK_TB) violated
    which I believe is because I updated those fields say ID = 1, all with 'Caroline'
    that means I will have to add a clause having count(TB.ID) = 1
    How would you do it?
    Server is Oracle 11g
    Thank you!

    Hi,
    One way is to join ta and tb in the USING clause, and eliminate the duplicates there.
    MERGE INTO     tb     dst
    USING   (
             SELECT    ta.id
             ,           REGEXP_SUBSTR ( MIN (ta.fullname)
                                    , '^[^,]*'
                            )     AS firstname
             FROM      ta
             JOIN      tb  ON  ta.id     = tb.id
             WHERE     ta.type      = 'ABC'
             GROUP BY  ta.id
             HAVING    COUNT (*)     = 1
         )                   src
    ON     (scr.id      = dst.id)
    WHEN MATCHED THEN UPDATE
    SET     dst.firstname     = src.firstname
    ;If you'd care to post CREATE TABLE and INSERT statements for your sample data, then I could test this.
    I used REGEXP_SUBST instead of SUBSTR and INSTR to find the firstname, because I find it a little cleaner, and becuase it returns something even when there is no ',' in fullname, which I'm guessing is what you really want. (None of the fullnames in your sample data have ','s.) You could use SUBSTR and INSTR instead.

  • Write an UPdate statement using the logic used in PL/SQL block (oracle 10g)

    Hi All,
    I have written the following PL/SQL block. I want to write an UPDATE statement using the logic used in the following PL/SQL block. can any one please help me out in this regards.
    DECLARE
       v_hoov_fag   gor_gold_post.hoov_flg%TYPE;
       v_b49n          gor_gold_post.b49n%TYPE;
       CURSOR c
       IS
          SELECT bs_id, loyalty_date, loyalty_period, contract_date
            FROM gor_gold_post
           WHERE tariff_code IN (169, 135, 136);
    BEGIN
       FOR rec IN c
       LOOP
          IF    (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period)
                        - SYSDATE) < 304
             OR (    TRUNC (  ADD_MONTHS (rec.loyalty_date, rec.loyalty_period)
                            - SYSDATE
                           ) IS NULL
                 AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2
          THEN
             v_hoov_flg := 1;
          ELSE
             v_hoover_flag := 99;
          END IF;
          IF    (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period)
                        - SYSDATE) < 121.6
             OR (    TRUNC (  ADD_MONTHS (rec.loyalty_date, rec.loyalty_period)
                            - SYSDATE
                           ) IS NULL
                 AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2
          THEN
             v_b49n := 1;
          ELSE
             v_b49n := 99;
          END IF;
          UPDATE gor_gold_post
             SET hoov_flg = v_hoov_flg,
                 b49n = v_b49n
           WHERE bs_id = rec.bs_id AND tariff_code IN (169, 135, 136);
          COMMIT;
       END LOOP;
    END;Thank you,

    Using case statement.
    UPDATE gor_gold_post
       SET hoov_flag = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 304
                                   OR
                                   (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
                                AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
                           THEN 1
                           ELSE 99
                         END,
           b49n      = CASE WHEN TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) < 121.6
                             OR
                             (TRUNC (ADD_MONTHS (rec.loyalty_date, rec.loyalty_period) - SYSDATE) IS NULL
                                AND (SYSDATE - TO_DATE (rec.contract_date, 'YYYYMMDD')) > 91.2)
                           THEN 1
                           ELSE 99
                         END
    WHERE tariff_code IN (169, 135, 136);Note: Code not tested.

  • How to update by using PL/SQL Records

    Hi,
    I want to update EMP table columns ename and empno only
    from other existing table TEST_EMP
    EMP table contains 14 rows.TEST_EMP table contains 3 rows.
    I need to update first three rows in EMP table.
    TEST_EMP DATA IS:
    ENAME EMPNO
    E1 1001
    E2 1002
    E3 1003
    Following code i written to update EMP table.
    DECLARE
    type r is record(id emp.empno%type,
         name emp.ename%type);
    r1 r;          
    BEGIN
    select ename,empno into r1 from test_emp;
    FOR i IN r1.FIRST .. r1.LAST
    LOOP
    update emp2
    set ename=r1(i).ename,
    empno=r1(i).empno
    WHERE empno = l_rc (i).empno;
    end loop;
    commit;
    EXCEPTION
    WHEN OTHERS
    THEN
    DBMS_OUTPUT.put_line (SQLERRM (SQLCODE));
    END;
    ERROR OCCURRED:
    ORA-06550: line 9, column 14:
    PLS-00302: component 'FIRST' must be declared
    ORA-06550: line 9, column 2:
    PL/SQL: Statement ignored
    I should use PL/SQL Record to update Table This is Mandatory.
    pls guide me.
    Regards,
    Venkat.

    > I want to update EMP table columns ename and empno only
    from other existing table TEST_EMP
    Why use PL/SQL and why use cursors?
    You are running a SELECT on the source table via the SQL engine and pulling that data from the db buffer cache into PL/SQL variables.
    Then you take that very same data, and push that back to the SQL engine using an UPDATE.
    So if you need to update 10KB worth of data, it means pulling 10KB from the SQL engine into the PL engine.. and then pushing 10KB of data from the PL engine back to the SQL engine.
    Not only pushing and pulling - you need your code to switch continually between the PL and SQL engines to do this.
    Now imagine doing it for 10MB of data.. or 1GB of data.. or more.
    Does it sound like your approach is effective? Does it sounds like it will perform well? Does it sound like it will scale?
    The basic rule for Oracle development is:
    Maximize SQL. Minimize PL/SQL (or Java or C#, etc).

  • Update record using SQL statement

    I have VB6.0 and Oracle 10G Express Edition in Windows 2000 Server. My procedure in VB 6.0 can't update record in the table using SQL statement, and the Error Message is " Missing SET keyword ".
    The SQL statement in VB6.0 look like this :
    General Declaration
    Dim conn as New ADODB.Connection
    Dim rs as New ADODB.Recordset
    Private Sub Command1_Click()
    dim sql as string
    sql = " UPDATE my_table " & _
    " SET Name = ' " & Text3.Text & " ' " & _
    " AND Unit = ' " & Text2.Text & " ' " & _
    " WHERE ID = ' " & Text1.Text & " ' "
    conn.Execute (sql)
    Private Sub Form Load()
    Set conn = New ADODB.Connection
    conn.Open "Provider=MSDASQL;" & "Data Source=my_table;"& "User ID =marketing;" & "Password=pass123;"
    I'm sorry about my language.
    What's wrong in my SQL statement, I need help ........ asap
    Best Regards,
    /Harso Adjie

    The syntax should be
    UPDATE TABLE XX
    SET FLD_1 = 'xxxx',
    FLD_2 = 'YYYY'
    WHERE ...
    'AND' is improperly placed in the SET.

  • Updates using single SQL Update statement.

    Hi Guys,
    I had an interview... and was not able to give an answer of one of the question.
    Given the emp table... need to update the salary with following requirement using one SQL statement...
    1. Update salary+1000 for those employees who have salary between 500 and 1000
    2. Update salary+500 for those employees who have salary between 1001 and 1500
    Both above requirement should be done by using only one SQL update statement... can some one tell me how to do it?

    update emp
      set salary   = case when salary between 500 and 1000
                                then salary + 1000
                                when salary between 1001 and 1500
                                then salary + 500
                          end;Regards
    Arun

  • HELP!!! Can't use sql:update in Netbeans Visual Web JSP

    I use Netbeans Visual Web in my project. I use Java DB database and Sun Java System Application Server 9.
    When i run my project, there is an error "The server encountered an internal error () that prevented it from fulfilling this request."
    Here is the codes:
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root version="1.2" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:ui="http://www.sun.com/web/ui" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:sql="http://java.sun.com/jsp/jstl/sql" >
    <jsp:directive.page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"/>
    <f:view>
    <ui:page binding="#{Page1.page1}" id="page1">
    <sql:update var="indata" dataSource="datasource">
    INSERT INTO "NBUSER"."user" ("Username") VALUES('jacky')
    </sql:update>
    <ui:html binding="#{Page1.html1}" id="html1">
    <ui:head binding="#{Page1.head1}" id="head1">
    <ui:link binding="#{Page1.link1}" id="link1" url="/resources/stylesheet.css"/>
    </ui:head>
    <ui:body binding="#{Page1.body1}" id="body1" style="-rave-layout: grid">
    <ui:form binding="#{Page1.form1}" id="form1"/>
    </ui:body>
    </ui:html>
    </ui:page>
    </f:view>
    </jsp:root>
    I can't store the data "jacky" into "Username" column in "user" table in database. Can anyone please let me know where is my mistake. Thanks.

    Maybe that SQL statement isn't valid. All those quotes look weird to me, but don't take that as meaning they are wrong. You should look in your server's logs to find out the actual error that occurred, rather than trying to guess what's wrong.

  • Unable to update wip resource usage rate using wip_txn_interface

    Hello All,
    I am unable to update wip resource usage rate using wip_txn_interface.
    The rows were processed in the interface table and Cost Manager also completed normal, but the rows were not updated.
    Can you please help?
    Thanks,
    Gani

    HI Gani,
    Is that stuck with any error?, please provide the error message if possible.
    Thanks,
    Raghav

  • SQLPS used to work before sql update

    I have a few .ps1 files being called from sql jobs that used to work and now i'm getting an error when the SQLPS module tries to load. The error specifically says: "...job step recieved an error at line 1 in Powershell script. The corresponding line
    is 'import module SQLPS -DisableNameChecking."
    The job step is running like this - 
    Start-Process PowerShell -ArgumentList "& 'C:\NewInstanceScripts\SPLA_Users.ps1'"
    The contents of the .ps1 file are as follows.  This and others like it work fine in ps direct. just not when called from a sql job.
    #Pull all group members into csv file
    Get-ADGroupMember “CRDS Users” | where {$_.objectclass-eq “user”} | Select SamAccountName | Export-csv -path C:\SPLA_Users.csv -NoTypeInformation  
    #Insert contents of csv into SQL table
    $sqlsvr = 'SQL03'
    $database = 'db_SPLA'
    $table = 'tbl_CRDSUsers'
    #Create SQL Connection
    Write-Verbose "Creating SQL Connection"
    $conn = New-Object System.Data.SqlClient.SqlConnection("Server=$SQLSvr;Database=$Database;Integrated Security=True")
    $conn.Open()
    $cmd = $conn.CreateCommand()
    #Create a delete statement if want to replace contents each time
    #$cmd2 = $conn.CreateCommand()
    #$cmd2.commandtext = "Delete From $table"
    #Write-Host -Fore Green "Clean Table Contents"
    #$cmd2.ExecuteNonQuery()
    Import-Csv C:\SPLA_Users.csv | % {
      #$_.Displayname
      #$_.Version
      #Create query string
      #Must matching the table layout (SoftwareName, Version)
      Write-Host -Fore Green "Inserting $_.SamAccountName into Table" 
      $cmd.CommandText = "INSERT INTO $table (SamAccountName,UploadDate) VALUES ('$($_.SamAccountName)', '$(get-date -f MM-dd-yyyy)')" 
      #Execute Query
      $cmd.ExecuteNonQuery() | Out-Null 
    The only thing i changed was the version of SQL Server 2012

    Hi Dave,
    Do you mean errors occured when calling a powershell script in SQL agent job?
    I'm also a little confused about the error, because I can not find the cmdlet "import-module SQLPS -DisableNameChecking" in the .ps1 file you posted above.
    Would you please post the hard code and its error information in detail, which will help us to troubleshoot?
    I recommend you can run the .ps1 file in powershell before calling in SQL agent job, and check if the script has any error.
    In addition, the script would get error, if there has UNC file path after running "import-Module 'sqlps'", for more detailed information, please check this thread:
    Powershell from a  SQL Agent Job (SQL Server 2012)
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna
    TechNet Community Support

  • Lookout OPC Client – Asynchronous I/O and Update Rate serious problems (Sequence of data)

    I am using the Lookout OPCClient driver to connect to AB PLCs (EtherNet/IP protocol) and power measurement equipment (Modbus TCP protocol). The OPC server is the NI OPC Servers. The data that are read out from PLCs and PMs are energy meter readings, energy counters, power, voltage, current, frequency, power factor and el. energy quality measurements (THD). That energy meter readings are being stored in SQL database.
    I am experiencing a serious problem regarding the accuracy of the meter readings. Several times per day, randomly, meter readings are losing the time sequence. For example, sequence is: 167, after few seconds 165, 166.  In other words, present value followed by two previous old values. That generates a serious problem in our application that is expecting a naturally rising sequence of counter values.
    Analyzing further, I isolated the problem to the connection between Lookout OPCClient and OPC Server. I made a simple application in Lookout 6.7 (opcproc.lkp, attached) with OPCClient parameters: NIOPCServers, OPC2, Asynchronus I/O, Update rate: 10000, Deadband: 0.0, that is reading just one tag from NI OPC Servers demo application (simdemo.opf).
    By using OPC diagnostic tool from NI OPC Servers I record the sequence of OPC requests and responses.  I found out that OPCClient sends every 2.5 sec “IOPCAsyncIO2::Refresh2()” call that is request for refreshing of all items in one OPC group. Few milliseconds later OPC Sever responds with callback function “IOPCDataCallback:: OnDataChange()(Device Refresh)” that actually refresh the data.
    This periodic sequence is intrinsic to the OPCClient and cannot be disabled or changed (by my knowledge).  This sequence is periodically interrupted by “IOPCDataCallback:: OnDataChange()” caused by update rate parameter of OPCClient (client is subscribed to server for periodic update of changed items).
    In the case of demo application on every 4 refresh callbacks caused by refresh requests (2.5 sec) there is one update subscription callback determined by Update rate (10 sec).
    QUESTION 1:
    What is the purpose of update sequence and update rate when we have every 2.5 sec fresh values?
    PROBLEM
    The problem arises when we have a large number of items in OPC group. In that case the OPC Server starts to queue refresh requests because they cannot be fulfilled in 2.5 sec time because of large number of I/O points that must be scanned. At the same time update subscription callbacks are running at the period determined by Update rate. I observed in my production system that regular update callbacks has higher priority than refresh callbacks from the queue. That causes the loosing of timed sequence of data. After the update callback with fresh data, sometimes follow one or two refresh callbacks from queue with old (invalid) data. By adjusting Update rate parameter (1 hour, 2hours …) I can postpone the collision of data refreshes but I cannot eliminate it. Furthermore, the 2.5 sec automatic refresh are large burden for systems with many I/O points.
    QUESTION 2:
    Is there a way to disable automatic refresh request every 2.5 sec and just use update requests determined by Update rate?
    QUESTION 3:
    Is there a way (or parameter) to change the period of automatic refresh (2.5 sec)?
    This problem is discovered for Lookout 6.5, 6.6 and 6.7 so I could say it is intrinsic to OPCClient. If I use synchronous I/O requests there is not an automatic refresh, but that is not an option for large systems.
    Thanks!
    Alan Vrana
    System engineer
    SCADA Projekt d.o.o.
    Picmanova 2
    10000 ZAGREB
    CROATIA
    T +385 1 6622230
    F +385 1 6683463
    e-mail [email protected]
    Alan Vrana
    SCADA Projekt d.o.o.
    ZAGREB, Croatia
    Attachments:
    opcproc.zip ‏4 KB

    The physical connection from LV to the switch is (I believe) copper crossover to fiber converter into a switch.  Then, fiber from the switch to the end device (relay).  The relay has all of the typical modbus registries and has been verified by inducing signals in to the system and measured/polled in LabVIEW and observed Variable Monitor.  I am working with LV 8.2 and 8.5. 
    An OPC server would only add an additional translation of addressing within the configuration.  The only real draw back would be the network overhead required to do this processing and not being representative of the end design configuration.
    I will reiterated my question in another way:
    I must answer the question to management that relates to data collection, test results and analysis; how often are you polling the client in relation to the outcomes measured?  At this time I can not point at any configuration in the set up and execution that directs the data framing rate.  I only measure the traffic and work with results.  This needs to be clearly identified based on the relay modbus/tcp design capability of supporting an fixed number of client requests per second. 
    For testing purposes, I would like to be able to stress the system to failure and have prove capabilities with measured data.  The present problem is that I have no basis to establish varying polling rates that effect the measured data transmission. 
    This raises another question.  What handles the Variable Monitor data requests and how is this rate determined?
    Thanks for your interest in my efforts.
    Steve

  • Problems Reading gas meter flow rate ni 9402 counter

    2015/07/13
    Can any one help with this?
    I have been trying to overcome the problem of the delay were a value is retained at the output of the counter for a period after the gas meter has stopped. This is causing me a problem as I am feeding this value into an integrator to get a measurement of energy used.(in the system I have other inputs such as gas pressure, barometric pressure and temperature)
    To solve this I decided to use the quadrature encoder input. I have taken the pulses from the gas meter and built a ripple counter from two JK flip flops (with logic to convert output to gray code) I have also added extra gates to counter propagation delay in the circuit. I am using a line driver IC SN75158PE4 at the output of the circuit. Can you see any problem with this method. I only ask because if I use X1 mode I get intermittent reading as in 0, reading, 0 reading etc. If I use X2 mode I get a value that I believe is correct but am still unsure about it. and in X4 mode I get a value that is lower than expected.?

    Some ideas:
    Monitor the raw DIO data showing the pulses, to make sure there are no spurious pulses after the flow is stopped or if there is any "bouncing" of the signal that might give a false hgh flow as the flow drops to zero - if there are you'll need to find something to deal with that.
    What is the max/min range of pulse speeds you are working with and are the default clocks used in the counters and the update rate for your flow /  energy calculations are all approrpiate - if you do the calcs faster the "delay" should be smaller ?
    Are you using DAQmx channels or DAQassistant to do programming - using DAQmx will give you much more flexibility on how the measurements are processed, and may be better
    I presume you are using a counter to produce a frequency output - if you switch to outputing the counter value itself, this will be the cumulative flow over time and that might be useable directly in your energy calculation without having to do an integration (assuming you are using the frequency to give flow rate (e.g. litres per second) which is being integrated). This might eliminate both any delay in seeing the measurement change and the effect of a delay on the integration.
    Hope this helps (and is understandable!)
     

  • Update statement using function

    Environment: Win7 and SQL server 2008 R2
    Tools: SQL management tool 2008 R2
    Problem: I have been trying to update id numbers in the staging table. T-SQL statement updates all id number in the staging table, but what if the we have multiple records for the same person who we are assigning the ID to his/her record. It should generate
    one pn_id per ssn regadless if there are several records for the same individual. for example, my code assigns the following id: 
    Student table (ID, ssn, name, subject, grade, year)
    (288258466,192160792 , Sally Johnson, Math, A, 2014 )
    (176268917, 192160792, Sally Johnson, Spanish, B+, 2014 )
    (900303787, 770616858, Jessica Simpson, Spanish, B, 2014 )
    (704099635, 770616858, Jessica Simpson, IT, A, 2014 )
    (704099640, 444718562, Douglas Mike, IT, A, 2014 )
    (288258450, 31883459, Susan Jesson, IT, A, 2014 )
    (176268960, 260518681, Veronica Floris, IT, A, 2014 )
    The expected results should be as the following in the staging table
    Student table (ID, ssn, name, subject, grade, year)
    (288258466,192160792 , Sally Johnson, Math, A, 2014 )
    (288258466, 192160792, Sally Johnson, Spanish, B+, 2014 )
    (900303787, 770616858, Jessica Simpson, Spanish, B, 2014 )
    (900303787, 770616858, Jessica Simpson, IT, A, 2014 )
    (704099640, 444718562, Douglas Mike, IT, A, 2014 )
    (288258450, 31883459, Susan Jesson, IT, A, 2014 )
    (176268960, 260518681, Veronica Floris, IT, A, 2014 )
    My code:
    UPDATE a
    SET pn_id = (Select dbo.gen_id())
    from [dbo].[Staging_Table] a
    where SSN in (Select SSN from [dbo].[staging_Table]
    group by SSN having count(SSN) > 1)
    GO
    I also tried the following code but no success
    ;with cte
    As
    Select * , ROW_NUMBER() Over(Partition BY ssn Order by ssn) As MyCount
    from dbo.Staging_Table
    Select * into #a from cte where MyCount=1
    UPDATE a
    SET pn_id = (Select dbo.fn_gen_id())
    from staging_table a
    Full join #a b on a.ssn = b.ssn
    Drop table #a
    please help.

    I ran some tests and Sandra is correct, you don't always get the same value for all occurrences of the same SSN.
    After thinking about this, I think I understand why this happens.
    With functions, SQL is allowed to assume that multiple calls to a function in a single command with the same parameter values always return the same result.  That's why functions cannot use side-effecting functions and is not allowed to make changes
    to any table except table variables declared in the function.
    And SQL is allowed to rearrange the processing of a command in any manner it believes is most efficient as long as it returns the same result.  So even though the query I gave says first get a set of distinct SSN's and then calls the function only once
    for each SSN, it is valid for SQL to instead call the function once for each row in the original table since this function has no parameters and is therefore should return the same value on each call.  But since the function being called apparently (we've
    not seen the code of the function) returns different values on different calls, the same SSN could be assigned different values, but SQL would still be working correctly.
    Note that it would also be valid for SQL to notice that this function has no parameters and therefore should return the same value every time it is called within the same command and so just call the function once per execution of the command.  This
    would mean that every SSN would get the same ID.  As far as I can determine currently SQL does not do that but a different version in the future with a different optimizer might.
    Tom

  • SQL Update statement taking too long..

    Hi All,
    I have a simple update statement that goes through a table of 95000 rows that is taking too long to update; here are the details:
    Oracle Version: 11.2.0.1 64bit
    OS: Windows 2008 64bit
    desc temp_person;
    Name                                                                                Null?    Type
    PERSON_ID                                                                           NOT NULL NUMBER(10)
    DISTRICT_ID                                                                     NOT NULL NUMBER(10)
    FIRST_NAME                                                                                   VARCHAR2(60)
    MIDDLE_NAME                                                                                  VARCHAR2(60)
    LAST_NAME                                                                                    VARCHAR2(60)
    BIRTH_DATE                                                                                   DATE
    SIN                                                                                          VARCHAR2(11)
    PARTY_ID                                                                                     NUMBER(10)
    ACTIVE_STATUS                                                                       NOT NULL VARCHAR2(1)
    TAXABLE_FLAG                                                                                 VARCHAR2(1)
    CPP_EXEMPT                                                                                   VARCHAR2(1)
    EVENT_ID                                                                            NOT NULL NUMBER(10)
    USER_INFO_ID                                                                                 NUMBER(10)
    TIMESTAMP                                                                           NOT NULL DATE
    CREATE INDEX tmp_rs_PERSON_ED ON temp_person (PERSON_ID,DISTRICT_ID) TABLESPACE D_INDEX;
    Index created.
    ANALYZE INDEX tmp_PERSON_ED COMPUTE STATISTICS;
    Index analyzed.
    explain plan for update temp_person
      2  set first_name = (select trim(f_name)
      3                    from ext_names_csv
      4                               where temp_person.PERSON_ID=ext_names_csv.p_id
      5                               and   temp_person.DISTRICT_ID=ext_names_csv.ed_id);
    Explained.
    @?/rdbms/admin/utlxpls.sql
    PLAN_TABLE_OUTPUT
    Plan hash value: 3786226716
    | Id  | Operation                   | Name           | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | UPDATE STATEMENT            |                | 82095 |  4649K|  2052K  (4)| 06:50:31 |
    |   1 |  UPDATE                     | TEMP_PERSON    |       |       |            |          |
    |   2 |   TABLE ACCESS FULL         | TEMP_PERSON    | 82095 |  4649K|   191   (1)| 00:00:03 |
    |*  3 |   EXTERNAL TABLE ACCESS FULL| EXT_NAMES_CSV  |     1 |   178 |    24   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       3 - filter("EXT_NAMES_CSV"."P_ID"=:B1 AND "EXT_NAMES_CSV"."ED_ID"=:B2)
    Note
       - dynamic sampling used for this statement (level=2)
    19 rows selected.By the looks of it the update is going to take 6 hrs!!!
    ext_names_csv is an external table that have the same number of rows as the PERSON table.
    ROHO@rohof> desc ext_names_csv
    Name                                                                                Null?    Type
    P_ID                                                                                         NUMBER
    ED_ID                                                                                        NUMBER
    F_NAME                                                                                       VARCHAR2(300)
    L_NAME                                                                                       VARCHAR2(300)Anyone can help diagnose this please.
    Thanks
    Edited by: rsar001 on Feb 11, 2011 9:10 PM

    Thank you all for the great ideas, you have been extremely helpful. Here is what we did and were able to resolve the query.
    We started with Etbin's idea to create a table from the ext table so that we can index and reference easier than an external table, so we did the following:
    SQL> create table ext_person as select P_ID,ED_ID,trim(F_NAME) fst_name,trim(L_NAME) lst_name from EXT_NAMES_CSV;
    Table created.
    SQL> desc ext_person
    Name                                                                                Null?    Type
    P_ID                                                                                         NUMBER
    ED_ID                                                                                        NUMBER
    FST_NAME                                                                                     VARCHAR2(300)
    LST_NAME                                                                                     VARCHAR2(300)
    SQL> select count(*) from ext_person;
      COUNT(*)
         93383
    SQL> CREATE INDEX EXT_PERSON_ED ON ext_person (P_ID,ED_ID) TABLESPACE D_INDEX;
    Index created.
    SQL> exec dbms_stats.gather_index_stats(ownname=>'APPD', indname=>'EXT_PERSON_ED',partname=> NULL , estimate_percent=> 30 );
    PL/SQL procedure successfully completed.We had a look at the plan with the original SQL query that we had:
    SQL> explain plan for update temp_person
      2  set first_name = (select fst_name
      3                    from ext_person
      4                               where temp_person.PERSON_ID=ext_person.p_id
      5                               and   temp_person.DISTRICT_ID=ext_person.ed_id);
    Explained.
    SQL> @?/rdbms/admin/utlxpls.sql
    PLAN_TABLE_OUTPUT
    Plan hash value: 1236196514
    | Id  | Operation                    | Name           | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | UPDATE STATEMENT             |                | 93383 |  1550K|   186K (50)| 00:37:24 |
    |   1 |  UPDATE                      | TEMP_PERSON    |       |       |            |          |
    |   2 |   TABLE ACCESS FULL          | TEMP_PERSON    | 93383 |  1550K|   191   (1)| 00:00:03 |
    |   3 |   TABLE ACCESS BY INDEX ROWID| EXTT_PERSON    |     9 |  1602 |     1   (0)| 00:00:01 |
    |*  4 |    INDEX RANGE SCAN          | EXT_PERSON_ED  |     1 |       |     1   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       4 - access("EXT_PERSON"."P_ID"=:B1 AND "RS_PERSON"."ED_ID"=:B2)
    Note
       - dynamic sampling used for this statement (level=2)
    20 rows selected.As you can see the time has dropped to 37min (from 6 hrs). Then we decided to change the SQL query and use donisback's suggestion (using MERGE); we explained the plan for teh new query and here is the results:
    SQL> explain plan for MERGE INTO temp_person t
      2  USING (SELECT fst_name ,p_id,ed_id
      3  FROM  ext_person) ext
      4  ON (ext.p_id=t.person_id AND ext.ed_id=t.district_id)
      5  WHEN MATCHED THEN
      6  UPDATE set t.first_name=ext.fst_name;
    Explained.
    SQL> @?/rdbms/admin/utlxpls.sql
    PLAN_TABLE_OUTPUT
    Plan hash value: 2192307910
    | Id  | Operation            | Name         | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
    |   0 | MERGE STATEMENT      |              | 92307 |    14M|       |  1417   (1)| 00:00:17 |
    |   1 |  MERGE               | TEMP_PERSON  |       |       |       |            |          |
    |   2 |   VIEW               |              |       |       |       |            |          |
    |*  3 |    HASH JOIN         |              | 92307 |    20M|  6384K|  1417   (1)| 00:00:17 |
    |   4 |     TABLE ACCESS FULL| TEMP_PERSON  | 93383 |  5289K|       |   192   (2)| 00:00:03 |
    |   5 |     TABLE ACCESS FULL| EXT_PERSON   | 92307 |    15M|       |    85   (2)| 00:00:02 |
    Predicate Information (identified by operation id):
       3 - access("P_ID"="T"."PERSON_ID" AND "ED_ID"="T"."DISTRICT_ID")
    Note
       - dynamic sampling used for this statement (level=2)
    21 rows selected.As you can see, the update now takes 00:00:17 to run (need to say more?) :)
    Thank you all for your ideas that helped us get to the solution.
    Much appreciated.
    Thanks

Maybe you are looking for