Update row in a table based on join on multiple rows in another table

I am using SQL Server 2005. I have the following update query which is not working as desired.
UPDATE DocPlant
SET DocHistory = DocHistory + CONVERT(VARCHAR(20), PA.ActionDate, 100) + ' - ' + PA.ActionLog + '. '
FROM PlantDoc PD INNER JOIN PlantAction PA on PD.DocID = PA.DocID AND PD.PlantID = PA.PlantID 
For each DocID and PlantID in PlantDoc table there are multiple rows in PlantAction table. I would like to concatenate ActionDate and ActionLog information into DocHistory column of DocPlant table. But the above update query is considering only one row from
PlantAction table even though there are multiple rows that match with DocID and PlantID.
DocHistory column is of type NVARCHAR(MAX).
How do I fix my query to achieve what I want ? Thanks for the help.

UPDATE DocPlant
SET DocHistory = DocHistory + CONVERT(VARCHAR(20), PA.ActionDate, 100) + ' - ' + PA.ActionLog + '. '
FROM PlantDoc PD INNER JOIN PlantAction PA on PD.DocID = PA.DocID AND PD.PlantID = PA.PlantID 
We do not use the old Sybase UPDATE..FROM.. syntax. Google it and learn how it does not work. We do not use the old Sybase CONVERT() string function. You are still writing 1950's COBOL with string dates instead of temeproal data types. 
You also did not post DDL, so we have to guess about everything. Does your boss make you work without DDL? How do you do it? 
>> For each DocID and PlantID in PlantDoc table there are multiple rows in PlantAction [singular name?] table. I would like to concatenate ActionDate and ActionLog information into DocHistory column of DocPlant table. <<
Why? What does this new data element mean? This is like dividing Thursday by Red and expecting a reasonable answer. Now, non-SQL programmers who are still writing COBOL will violate the tiered architecture rule about doing display formatting in the database.
If you will follow forum rules, we can help you. 
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • How can i update rows  in a table based on a match from a select query

    Hello
    How can i update rows in a table based on a match from a select query fron two other tables with a update using sqlplus ?
    Thanks Glenn
    table1
    attribute1 varchar2 (10)
    attribute2 varchar2 (10)
    processed varchar2 (10)
    table2
    attribute1 varchar2 (10)
    table3
    attribute2 varchar2 (10)
    An example:
    set table1.processed = "Y"
    where (table1.attribute1 = table2.attribute1)
    and (table1.attribute2 = table3.attribute2)

    Hi,
    Etbin wrote:
    Hi, Frank
    taking nulls into account, what if some attributes are null ;) then the query should look like
    NOT TESTED !
    update table1 t1
    set processed = 'Y'
    where exists(select null
    from table2
    where lnnvl(attribute1 != t1.attribute1)
    and exists(select null
    from table3
    where lnnvl(attribute2 != t1.attribute2)
    and processed != 'Y'Regards
    EtbinYes, you could do that. OP specifically requested something else:
    wgdoig wrote:
    set table1.processed = "Y"
    where (table1.attribute1 = table2.attribute1)
    and (table1.attribute2 = table3.attribute2)This WHERE clause won't be TRUE if any of the 4 attribute columns are NULL. It's debatable about what should be done when those columns are NULL.
    But there is no argument about what needs to be done when processed is NULL.
    OP didn't specifically say that the UPDATEshould or shouldn't be done on rows where processed was already 'Y'. You (quite rightly) introduced a condition that would prevent redo from being generated and triggers from firing unnecessarily; I'm just saying that we have to be careful that the same condition doesn't keep the row from being UPDATEd when it is necessary.

  • Cursor and Update rows based on value/date

    SQL Server 2012
    Microsoft SQL Server Management Studio
    11.0.3128.0
    Microsoft Analysis Services Client Tools
    11.0.3128.0
    Microsoft Data Access Components (MDAC)
    6.1.7601.17514
    Microsoft MSXML 3.0 4.0 5.0 6.0 
    Microsoft Internet Explorer
    9.11.9600.16518
    Microsoft .NET Framework
    4.0.30319.18408
    Operating System
    6.1.7601
    The objective of this is to test the Cursor and use it on a production environment after this is fixed. What I would like to do is update rows in a column i duplicated originally called 'HiredDate' from AdventureWorks2012 HumanResources.Employee table. I
    made a duplicate column called 'DateToChange' and would like to change it based on a date I have picked, which returns normally 2 results (i.e. date is '04/07/2003'). The code runs but will not change both dates. It did run however with an error but changed
    only 1 of the 2 rows because it said ['nothing available in next fetch'].
    The code to add the columns and perform the query to get the results I am running this against:
    -- ADD column 'DateToChange'
    ALTER TABLE [HumanResources].[Employee] ADD DateToChange Date NOT NULL;
    -- Copy 'HireDate' data to 'DateToChange'
    UPDATE HumanResources.Employee SET DateToChange = HireDate;
    -- Change 'DateToChange' to NOT NULL
    ALTER TABLE [HumanResources].[Employee] ALTER COLUMN DateToChange Date NOT NULL;
    SELECT BusinessEntityID,HireDate, CONVERT( char(10),[DateToChange],101) AS [Formatted Hire Date]
    FROM HumanResources.Employee
    WHERE [DateToChange] = '04/07/2003';
    Code:
    USE AdventureWorks2012;
    GO
    -- Holds output of the CURSOR
    DECLARE @EmployeeID INT
    DECLARE @HiredDate DATETIME
    DECLARE @HiredModified DATETIME
    DECLARE @ChangeDateTo DATETIME
    --Declare cursor
    -- SCROLL CURSOR ALLOWS "for extra options" to pul multiple records: i.e. PRIOR, ABSOLUTE ##, RELATIVE ##
    DECLARE TestCursor CURSOR SCROLL FOR
    -- SELECT statement of what records going to be used by CURSOR
    -- Assign the query to the cursor.
    SELECT /*HumanResources.Employee.BusinessEntityID, HumanResources.Employee.HireDate,*/ CONVERT( char(10),[DateToChange],101) AS [Formatted Hire Date]
    FROM HumanResources.Employee
    WHERE DateToChange = '01/01/1901'
    /*ORDER BY HireDate DESC*/ FOR UPDATE OF [DateToChange];
    -- Initiate CURSOR and load records
    OPEN TestCursor
    -- Get first row from query
    FETCH NEXT FROM TestCursor
    INTO @HiredModified
    -- Logic to tell the Cursor while "@@FETCH_STATUS" 0 the cursor has successfully fetched the next record.
    WHILE (@@FETCH_STATUS = 0 AND @@CURSOR_ROWS = -1)
    BEGIN
    FETCH NEXT FROM TestCursor
    IF (@HiredModified = '04/07/2003')/*05/18/2006*/
    -- Sets @HiredModifiedDate data to use for the change
    SELECT @ChangeDateTo = '01/01/1901'
    UPDATE HumanResources.Employee
    SET [DateToChange] = @ChangeDateTo --'01/01/1901'
    FROM HumanResources.Employee
    WHERE CURRENT OF TestCursor;
    END
    -- CLOSE CURSOR
    CLOSE TestCursor;
    -- Remove any references held by cursor
    DEALLOCATE TestCursor;
    GO
    This query is run successfully but it does not produce the desired results to change the dates
    04/07/2003 to 01/01/1901.
    I would like the query to essentially be able to run the initial select statement, and then update and iterate through the returned results while replacing the necessary column in each row.
    I am also open to changes or a different design all together. 
    For this query I need:
    1. To narrow the initial set of information
    2. Check if the information returned, in particular a date, is before [i.e. this current month minus 12 months or
    12 months before current month]
    3. Next replace the dates with the needed date
    [Haven't written this out yet but it will need to be done]
    4. After all this is done I will then need to update a column on each row:
    if the 'date' is within 12 months to 12 months from the date checked
    NOTE: I am new to TSQL and have only been doing this for a few days, but I will understand or read up on what is explained if given enough information. Thank you in advance for anyone who may be able to help.

    The first thing you need to do is forget about cursors.  Those are rarely needed.  Instead you need to learn the basics of the tsql language and how to work with data in sets.  For starters, your looping logic is incorrect.  You open
    the cursur and immediately fetch the first row.  You enter the loop and the first thing in the loop does what?  Fetches another row.  That means you have "lost" the values from the first row fetched.  You also do not test the success of
    that fetch but immediately try to use the fetched value.  In addition, your cursor includes the condition "DateToChange = '01/01/1901' " - by extension you only select rows where HireDate is Jan 1 1901.  So the value fetched into @HiredModified will
    never be anything different - it will always be Jan 1 1901.  The IF logic inside your loop will always evaluate to FALSE.  
    But forget all that.  In words, tell us what you are trying to do.  It seems that you intend to add a new column to a table - one that is not null (ultimately) and is set to a particular value based on some criteria.  Since you intend the
    column to be not null, it is simpler to just add the column as not null with a default.  Because you are adding the column, the assumption is that you need to set the appropriate value for EVERY row in the table so the actual default value can be anything.
     Given the bogosity of the 1/1/1901 value, why not use this as your default and then set the column based on the Hiredate afterwards.  Simply follow the alter table statement with an update statement.  I don't really understand what your logic
    or goal is, but perhaps that will come with a better description.  In short: 
    alter table xxx add DateToChange date default '19010101'
    update xxx set DateToChange = HireDate where [some unclear condition]
    Lastly, you should consider wrapping everything you do in a transaction so that you recover from any errors.  In a production system, you should consider making a backup immediately before you do anything - strongly consider and have a good reason not
    to do so if that is your choice (and have a recovery plan just in case). 

  • Select query based on joining of tables from different database is taking too long

    Hi Team,
    Select query on table with millions of records is taking very long time. It took 50mins, the below query is joining on multiple table from two databases DB1.dbo.Table1 contains 100 million records and also Table3 and Table4 (of different database) might
    contain close to 1million records.
    Select T1.*
    From DB1.dbo.Table1 T1
    Join DB1.dbo.Table2 T2 on RTRIM(T1.Col3) = RTRIM(T2.Col3)
    Join Table4 CA on RTRIM(T1.Col1) + T2.Col2 = CA.Col1
    Join Table3 U on CA.Col2 = U.Col2 AND RTRIM(T2.Col2) = U.Col3
    Where U.Col4 NOT IN ('A1', 'A2', 'A3', 'A4', 'A5', 'A6','A7','A8','A9')
    And (T1.flg IS NULL OR T1.flg = 'N')
    And LTRIM(RTRIM(T2.Col2)) NOT IN ('B1','B2')
    How can i improve the performance of this query. Actual thing is update the data in Db1.dbo.table1 based on the conditions but if the select is taking close to 1hr then update will take hours together. Indexes already implemented on all the tables.
    Thanks,
    Eshwar.
    Please don't forget to Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful. It will helpful to other users.

    Thanks.
    Join Table4 CA on RTRIM(T1.Col1) + T2.Col2 = CA.Col1
    This join is not working with spaces if Rtrim is not used.
    Thanks! Eshwar.
    Please don't forget to Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful. It will helpful to other users.

  • How to find  latest updating row in a table

    Hi
    How to find latest updating row in a table

    ADF 7 wrote:
    SELECT *  FROM Table WHERE lastupdTimestamp = (SELECT MAX(lastupdTimestamp) FROM Table)lastupdtimestamp - holds and date an time of an records when it last updation takes place in table.
    lastupdtimestamp is a column in my table.And how will this make sense in the scenario I've described, where UserA does an update before UserB, but commits the update after UserB's commited update? And add UserC and UserD and a 1000 more users to this scenario where concurrent updates happen.
    What actual time does this lastupdtimestamp contain and represent? And why? How is that lastupdtimestamp used in business logic and processing? Or is it just a silly-bugger-let's-add-somekind-of-time column to that table that essentially meaningless?
    Not saying that one should never add such a timestamp based column. Simply that one needs to understand WHAT it contains and it needs to be SENSIBLY used within the data model.
    However, in my experience such columns are often slapped on afterwards, never featured in the actual data model designed, and is then used without a second though that the database and its data is a multi-user and multi-process system. And things happen at the same time. And things overlap (serialisation is the exception - not the rule).

  • How to Find Source Table Updated Rows using Tsql Script

    Hi Folks,
    i have 2 tales Source table and Staging Table. yeaterday I have Imported 24 Million Records From Source table into Staging table. These Table Contain approxmately 42 columns. So today may be some of the updates happend  in Source table rows. ID is the
    Unique column.
    So may I know which rows are Updated compared to Both tables using Tsql Query. (all 42 Columns might be updated ) .
    usually new rows also appeard in sourcetable. I want only Which are Updated not New rows!.
    Thanks in Advance.

     SELECT Source.*, Stage.*
       FROM Source
            FULL OUTER JOIN
            Stage
            ON Source.c1 = Stage.c1
               AND Source.c2 = Stage.c2
               AND Source.cn = Stage.cn
     WHERE Source.key IS NULL 
        OR Stage.key IS NULL; 
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Need help in SQL Query: Update a row in a table & insert the same row into another table

    I want to update a row in a table say Table A and the updated row should be inserted into another table say Table B. I need to do it in a single SQL query and i don't want to do it in PL/SQL with triggers. And i tried with MERGE statement but its working with this scenario. (Note: I'm using Oracle Database 10g Enterprise Edition Release 10.2.0.1.0).
    Thanks in Advance.

    Using Sven's code as an example, you could save the updated row in a sql plus variable. (also untested):
    SQL> var v_id number
    update tableA  
    set colB='ABC' 
    where colC='XYZ' 
    returning id into :v_id;
    insert into table A_History (ID, colA, colB, ColC)  
    select id, ColA, ColB, ColC  
    from tableA  
    where id = :v_id;   

  • How to find newly updated rows in a table

    Hi..
    How to know newly updated rows in a table.
    Thanks in advance
    pal

    Or other good thing would be to add LAST_UPDATED column to your table, that can reflect the time the row gets updated.
    G

  • Update Rows with info from other Rows in Same Table.

    I'm trying to update rows with information from the same table. The table gets loaded with info from a report that runs and it has to be a new entry every month but I would like to carry over some of the info from last month. This statement below runs but updates all rows in the new table load and in my test cases I only made a few match so only like 5 records should get updated. This is an example of what I'm trying to do. If I add this(C2.COL_INVC_ID = C1.COL_INVC_ID) to the last "*Where*" statement I get an invalid identifier for "C2.COL_INVC_ID". So what am I doing wrong here??? How can I update only the rows that where also in last months run???
    Thanks in advance for any help!
    Update OpenIssues OI1
    Set(OI1.Num, OI1.Status, OI1.Code, OI1.LastModifiedDate) =
    (Select OI2.Num, OI2.Status, OI2.Code, OI2.LastModifiedDate
    From OpenIssues OI2
    Where OI2.num = OI1.num and OI2.TableLoadDate = TO_DATE('01/31/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    Where and OI1.TableLoadDate = TO_DATE('02/29/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    SQLMe

    Hi,
    Welcome to the forum!
    SQLMe wrote:
    I'm trying to update rows with information from the same table. The table gets loaded with info from a report that runs and it has to be a new entry every month but I would like to carry over some of the info from last month. This statement below runs but updates all rows in the new table load and in my test cases I only made a few match so only like 5 records should get updated. This is an example of what I'm trying to do. If I add this(C2.COL_INVC_ID = C1.COL_INVC_ID) to the last "*Where*" statement I get an invalid identifier for "C2.COL_INVC_ID". If the aliases c1 and c2 aren't defined anywhere, then you can't use them anywhere.
    The WHERE clause of the UPDATE statement can only reference the table being updated, ot1 in this case.
    So what am I doing wrong here??? How can I update only the rows that where also in last months run???
    Thanks in advance for any help!
    Update OpenIssues OI1
    Set(OI1.Num, OI1.Status, OI1.Code, OI1.LastModifiedDate) =
    (Select OI2.Num, OI2.Status, OI2.Code, OI2.LastModifiedDate
    From OpenIssues OI2
    Where OI2.num = OI1.num and OI2.TableLoadDate = TO_DATE('01/31/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    Where and OI1.TableLoadDate = TO_DATE('02/29/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS')
    ------------There's a syntax error in the last line. Either something got lost when you posted the code, or you just don't want the keyword AND. You certainly don't want AND immediately after WHERE.
    In general, if it's not obvious how to do an UPDATE, then UPDATE is the wrong tool: you want MERGE instead.
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Simplify the problem as much as possible. Remove all tables and columns that play no role in this problem.
    If you're asking about a DML statement, such as UPDATE, the CREATE TABLE and INSERT statements should re-create the tables as they are before the DML, and the results will be the contents of the changed table(s) when everything is finished.
    Always say which version of Oracle you're using.
    See the forum FAQ {message:id=9360002}

  • Update Row into Run Table Task is not executing in correct sequence in DAC

    Update Row into Run Table Task is not executing in correct sequence in DAC.
    The task phase for this task is "Post Lost" . The depth in the execution plan is 19 but this task is running some times in Depth 12, some times in 14 and some time in Depth 16. Would like to know is this sequence of execution is correct order or not? In the out of the Box this task is executed at the end of the entire load. No Errors were reported in DAC log.
    Please let me know if any documents that would highlight this issue
    rm

    Update into Run table is a task thats required to update a table called W_ETL_RUN_S. The whole intention of this table is to keep the poor mans run history on the warehouse itself. The actual run history is stored in the DAC runtime tables, however the DAC repository could be on some other database/schema other than warehouse. Its mostly a legacy table, thats being carried around. If one were to pay close attention to this task, it has phase dependencies defined that dictate when this task should run.
    Apologies in advance for a lengthy post.... But sure might help understanding how DAC behaves! And is going to be essential for you to find issues at hand.
    The dependency generation in DAC follows the following rules of thumb!
    - Considers the Source table target table definitions of the tasks. With this information the tasks that write to a table take precedence over the tasks that reads from a table.
    - Considers the phase information. With this information, it will be able to resolve some of the conflicts. Should multiple tasks write to the same table, the phase is used to appropriately stagger them.
    - Considers the truncate table option. Should there be multiple tasks that write to the same table with the same phase information, the task that truncates the table takes precedence.
    - When more than one task that needs to write to the table that have similar properties, DAC would stagger them. However if one feels that either they can all go in parallel, or a common truncate is desired prior to any of the tasks execution, one could use a task group.
    - Task group is also handy when you suspect the application logic dictates cyclical reads and writes. For example, Task 1 reads from A and writes to B. Task 2 reads from B and writes back to A. If these two tasks were to have different phases, DAC would be able to figure that out and order them accordingly. If not, for example those tasks need to be of the same phase for some reason, one could create a task group as well.
    Now that I described the behavior of how the dependency generation works, there may be some tasks that have no relevance to other tasks either as source tables or target tables. The update into run history is a classic example. The purpose of this task is to update the run information in the W_ETL_RUN_S with status 'Completed' with an end time stamp. Because this needs to run at the end, it has phase dependency defined on it. With this information DAC will be able to stagger the position of execution either before (Block) or after (Wait) all the tasks belonging to a particular phase is completed.
    Now a description about depth. While Depth gives an indication to the order of execution, its only an indication of how the tasks may be executed. Its a reflection of how the dependencies have been discovered. Let me explain with an example. The tasks that have no dependency will have a depth of 0. The tasks that depend on one or more or all of depth 0 get a depth of 1. The tasks that depend on one or more or all of depth 1 get a depth of 2. It also means implicitly a task of depth 2 will indirectly depend on a task of depth 0 through other tasks in depth 1. In essence the dependencies translate to an execution graph, and is different from the batch structures one usually thinks of when it comes to ETL execution.
    Because DAC does runtime optimization in the order in which tasks are executed, it may pick a task thats of order 1 over something else with an order of 0. The factors considered for picking the next best task to run depend on
    - The number of dependent tasks. For example, a task which has 10 dependents gets more priorty than the one whose dependents is 1.
    - If all else equal, it considers the number of source tables. For example a task having 10 source tables gets more priority than the one that has only two source tables.
    - If all else equal, it considers the average time taken by each of the tasks. The longer running ones will get more preference than the quick running ones
    - and many other factors!
    And of course the dependencies are honored through the execution. Unless all the predecessors of a task are in completed state a task does not get picked for execution.
    Another way to think of this depth concept : If one were to execute one task at a time, probably this is the order in which the tasks will be executed.
    The depth can change depending on the number of tasks identified for the execution plan.
    The immediate predecessors and successor can be a very valuable information to look at and should be used to validate the design. All predecessors and successors provide information to corroborate it even further. This can be accessed through clicking on any task and choosing the detail button. You will see all these information over there. As an alternate method, you could also use the 'All/immediate Predecessors' and 'All/immediate Successor' tabs that provide a flat view of the dependencies. Note that these tabs may have to retrieve a large amount of data, and hence will open in a query mode.
    SUMMARY: Irrespective of the depth, validate
    - if this task has 'Phase dependencies' that span all the ETL phases and has a 'Wait' option.
    - click on the particular task and verify if the task does not have any successors. And the predecessors include all the tasks from all the phases its supposed to wait for!
    Once you have inspected the above two you should be good to go, no matter what the depth says!
    Hope this helps!

  • Is it possible to update attributes in all tables in a multi entity view

    Hi I have a view based on 4 entities, all of which are a 3 of which are 1 to many relationship with the 4th. The 3 additional entities have 2 or 3 attributes, Id, name, and one entity has a foreign key relating to a different table which I do not care about. The IDs are all updatable in the entity, and none of them are generated from a sequence but are inserted manually, except for the 4th (Master?) which is generated from a sequence.
    I create the view and all the entities are updatable, but in the view when I go to attributes from the other tables, it says updatable never and is grayed out so I cannot change it, even though in the entities tab, it is updatable always.
    So I was wondering if this was possible to do???

    I do not understand really, if it is 2 different tables, it is 2 different primary keys. Why would this even happen? What does it matter if EmployeeID and DepartmentID is both 1??? It just seems that there has to be a simpler way to do this but ok.
    So I go to the AppModule, Java tab and go generate Java class. The original code was
    public ViewObjectImpl getObjektiCRUDView1()
    return (ViewObjectImpl)findViewObject("ObjektiCRUDView1");
    I then copy your code to the best of my limited knowledge and get this
    public ViewObjectImpl getObjektiCRUDView1()
    this.getObjektiCRUDView1().executeEmptyRowSet();
    {Row yourRow = this.getObjektiCRUDView1().createRow();
    this.getObjektiCRUDView1().insertRow(yourRow );
            return (ViewObjectImpl)findViewObject("ObjektiCRUDView1");
    On the first row the getObjektiCRUDView1() is underlined and it says missing method body or declare as abstract.
    I know I did something wrong here but I have no idea what as I am not very good with Java
    Also it is not a jsf page, I create a single jspx page and divided it using the panel splitter so on one side we have an adf table for updating the Objekti database table, and on the other side I have an adf form for updating the Positions table (and later on other tables, I hope to have many forms there)
    Edited by: Dino2dy on Jun 10, 2010 12:02 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Synchronizing Updates on a Staging Table

    Please help me out with the resolving the following issue:
    A load script is running for moving records from a data file to a staging table.
    After this script completes, there is a code to update two fields of the staging table.
    To do this the shell script runs a script (generate_ranges.sql). It takes a parameter of 5000000. It creates ranges based on this passed in number upto the total number of rows in the staging table. So say the staging table has 65,000,000 rows.
    This script will create a file that looks like the following (when 5000000 is passed in):
    1 | 5000000
    5000001 | 10000000
    10000001 | 15000000
    15000001 | 20000000
    20000001 | 25000000
    25000001 | 30000000
    30000001 | 35000000
    35000001 | 40000000
    40000001 | 45000000
    45000001 | 50000000
    50000001 | 55000000
    55000001 | 60000000
    60000001 | 65000000
    The script goes on to read the data file for each row and it calls a shell script and passes in each range. So in this case there are 13 ranges. What is happening is there are 13 seperate updates on the staging table happening in the background.
    The first update rows 1 - 5000000, the second rows 5000001 - 10000000 etc.
    So there are 13 updates happenng behind the scenes.
    The problem is that there is no way for the script to know that all updates are completed successfully before proceeding automatically. Right now I manually check to see that that all updates completed and then I restart the script at the next step. However we want to code to ensure that all the updates are done automatically and then move on in the script. So we need a way to count the number of candidate updates ( right now 13 but could be 14 or more in future) and know that all "x" updates completed, it may be the case that update (1-5000000) is taking 30 mins and the next update ( 5000001 - 10000000) is taking 35 mins, all updates iare running parallely, and only when after the 13 parallel updates are complete, the script can proceed with subsequent steps.
    So please help me out with fixing this problem programmatically.
    Thanks for your cooperation in advance.
    Regards,
    Ayan.

    Ayan,
    Are you really sure you want to update 65 million rows ?
    Alternative: create table as select <columns with 2 columns updated> from staging table;
    While using this approach, you probably don't need to split the update.
    Regards,
    Rob.

  • SQL Bulk Update using Update query in SQL Table

    Hello All,
    I want to update data in sql table depends on some condition.
    I am getting excel sheet from client and want to change value of field say Status = c.
    Client is sending excel sheet with 300 field and want to change value for all 300 records with unique fields (field1 and field2) comming in that excel sheet...
    How can i write and update records as Bulk.
    Instaed updating one one recors ?
    Example ( Update Table_Name Set Status = 'c' Where Field1 = Value from Excel for Field1 and
    Field2 = Value from Excel for Field2 )
    Same needs to do for 300 records...
    Any help will wellcome.
    Thanks,
    Nilesh....
    Thanks and Regards, Nilesh Thakur.

    you can use OPENROWSET for that
    http://www.mssqltips.com/sqlservertip/1540/insert-update-or-delete-data-in-sql-server-from-excel/
    Another way is to use SSIS with data flow task having Excel source connecting to excel and using OLEDB command to update rows in table using it. You may also use staging table to get data from excel and later use it inexecute sql task to update your table
    to make update set based which would be faster.
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Update query for Advanced table.

    Hi,
    I am an newbie to OAF so need help for a simple task.
    I have an advanced table that has been created using expert mode query of VO. (as it contains data from more than one table).
    Now, i want to update the data for any row that is changed in the table,
    i followed the advanced table example in the tutorial and reached till the update method of AM. Now I am not able to update the table. When I searched the forum it said that I need to have a simple EO on the table to update it, but I want to update more than one table ( foreign key relationship), so can I do it using the same VO ? I have both the VO (one based on custom select query of Expert mode and other normal VO based on EO).
    Can someone please give me the query to update the table ?
    Thanks,
    VK

    Thanks Reetesh for your reply.
    As this is a simple task I wan't to do it via OAF query rather than writing PL/SQL procedure.
    I have two tables , say error table and interface table, (there is a foreign key relation ship between these tables, ie. i have to show the interface name present in the interface table via the foreign key in the error table). I used the following query to get the data
    SELECT xxgblErrorMasterEO1.ERROR_ID_NO,
    xxgblErrorMasterEO1.ERROR_CODE,
    xxgblErrorMasterEO1.ERROR_MESSAGE,
    xxgblErrorMasterEO1.CREATED_BY,
    xxgblErrorMasterEO1.CREATION_DATE,
    xxgblErrorMasterEO1.LAST_UPDATED_BY,
    xxgblErrorMasterEO1.LAST_UPDATE_DATE,
    xxgblIntfProgramMaster.INTERFACE_NAME,
    xxgblErrorMasterEO1.ERROR_TYPE
    FROM XXEEG.XXGBL_ERROR_MASTER xxgblErrorMasterEO1,
    XXEEG.XXGBL_INTF_PROGRAM_MASTER xxgblIntfProgramMaster
    where xxgblErrorMasterEO1.INTERFACE_ID_NO =
    xxgblIntfProgramMaster.INTERFACE_ID_NO
    I like the idea of Advanced table while going through the tutorial (example 2) and would want to show certain fields by expanding on the + mark ( just like in the explorer)
    now i want to update any of the fields that i show to the user (except the WHO fields). Say for example if the user updates the error_message and Interface_name, so how should i write the update method in the AM ?
    Pardon me if this sounds simple :(

  • Join of Multiple Tables

    We are experiencing an unpredictable error in a simple form and have
    experimented it in different scenarios it behaves in the same way.
    The problem description is as under:
    We are using "Join of Multiple Tables" feature of Developer-6i. In our
    forms there are two tables e.g. Emp and Dept. We have set all the
    properties requiered to do this job inluding:
    1. "Query Data Source Name" is set to Emp,Dept.
    2. "Where Cluase" is set to Emp.Deptno = Dept.Deptno
    3. "DML Target Name" is set to EMP.
    4. Manullay created the columns for Dept.Dname.
    5. Set the Query-Only Property to Yes.
    6. Set the Primary Key Property to Yes for Empno
    When we execute this form it performs properly with the normal operations.
    It inserts, updates and delete records properly But in the scenario e.g.
    when we scroll to 5th or any other record greater this number and
    start changing employee name and committing on the each record going
    backward. It generates Primary Key Violation errors after updating
    4-5 records.
    When we locate the error in "Display Error" button it shows the update
    statement as "UPDATE EMP SET WHERE ROWID=:1" and there is no "Field=Value"
    cluase in the UPDATE statement.

    Hi, Mahesh,
    So you want only 1 row of output for each distinct combination of currentpress and lastpcirim?  That sounds like a job for GROUP BY.
    And you want that row to contain a delimited list of all the different typidcontainers?  That sounds like a job for the aggregate LISTAGG function.
    WITH  joined_data  AS
        SELECT DISTINCT
                    mst.curepress, mst.lastpcirim, inf.typeidcontainer
        FROM        betmaster mst
        LEFT JOIN   betinfo   inf   ON  TRIM (mst.curepress) = SUBSTR ( TRIM (inf.currentpress)
                                                                      , 1
                                                                      , 3
    SELECT    curepress, lastpcirim
    ,         LISTAGG (typeidcontainer, ', ')
                  WITHIN GROUP (ORDER BY  typeidcontainer)   AS container_list
    FROM      joined_data
    GROUP BY  curepress, lastpcirim
    Unfortunately, you can't say LISTAGG (DISTINCT ...), so you still have to get the distinct containers the way you're already doing it.  (Notice that the sub-query is just what you posted.)
    Thanks for posting the CREATE TABLE and INSERT statements; that's very helpful.  Don't forget to say which version of Oracle you're using.  LISTAGG was new in Oracle 11.2.
    Why not add CHECK constraints (and maybe triggers) to your tables, so that curepress and currentpress are not stored with leading or trailing spaces?  Then you wouldn't need to use TRIM in queries like this, and your code would be simpler and more efficient.

Maybe you are looking for

  • HT1386 My new iPhone 5S will no longer sync to my iTunes library on my computer.

    When I first bought my iPhone 5S a couple monhts ago, my music libraray came over just fine from my old Iphone. And I was able to sync to my computer iTunes libraray for updates (new songs and playlists, etc,) a couple times. But now, sync don't work

  • Can not add songs to ipod--says not space when there should be

    I have deleted many, many songs from my ipod but when I try to add just one song, I get the message that there is not enough space for the file. Also, the space available is not going down when I delete songs. Help!! Do I need to delete everything an

  • String object to Date object

    Hi, I have date as string object "22/04/2008". I want convert this string object to Date object as specified format (dd/MM/yyyy) only. Please do the need full. Thanks in Advance

  • Does Elements 11 and Lightroom 5 integrate simply together?

    My friend has CS5 on his computer and when I play with it very ocasionally I find it a total nightmare and run a mile.  I just don't understand it.   Not wanting to waste my money (Yorkshireman!), I see the need for a Photoshop product to help remove

  • Transformation Questions

    Hello I'm getting an ERROR in the following transformations rule.. Timestamp --> Date Timestamp --> time Timestamp --> Month Timestamp --> Year I though time info Objects are subjected to automatic conversions ?, why its is NOT getting converted ? Th