Update rows in Database reading field in rows of selectoneListBox

JDev 11.1.1.4, application JSF.
I have a .jspx that contain a af:table with 20 rows. These rows are read from database.
I have (in the same .jspx) a af:selectoneListBox with f:selectItems.
I use drag and drop from table to selectoneListBox. I save into af:selectItems the first field of each row choice.
Now, how can I put a button than when I press it, it makes a change in database (View Objects) passing as parameter the field reads in row of selectoneListBox.
Thanks

Thanks for your replay Kamaal,
but I have thought another way.
I'd like to write something like:
update filea set field1='1' where field2 in (getSelectedItems())
where getSelectedItems() contain the fields read in rows of selectoneListBox.
But, I do not know where I have to write this sql statement and then how to execute it by pressing a button, maybe in the ViewObjectImpl ? and if yes, how?
Thanks

Similar Messages

  • Jdev Database Adapter - polling updated rows

    Hello, I have a question reguarding the polling strategy available in the database adapter.
    I set it up and it works great with new inserted rows in the table.
    However, it doesn´t capture the updated rows!
    For instance, i have the following table:
    ID - NAME - AGE
    1 -John- 21
    2 -Mary- 25
    When I insert a new row, it is captured by comparing the last captured ID in the sequencing file.
    ID - NAME - AGE
    1 -John- 21
    2 -Mary- 25
    3 -Cindy- 20 <--------- New row
    But when i UPDATE an already existing row, it doesnt load the changed row!
    ID - NAME - AGE
    1 -John- 26 <----------- Age changed, but polling doesnt recognize it!
    2 -Mary- 25
    3 -Cindy- 20
    Is there a way to get this to work? Should I set an special option? Thank you very much.
    Im using jdeveloper 11g.

    Hi John, it depends on which type of polling strategy you are using to poll the new/updated records. You must have the necessary previleges to add the special field and creat triggers or your db team must have.
    i.Physical delete polling strategy: Cannot capture the UPDATE operations on the table.This because when the adapter listens to the table, when ever a record is polled, that record is deleted after the polling process. After polling the records, if it is not deleted, then the adapter knows that it’s a updated one but here when a record is polled, it is deleted. So when an adapter encounters a record, it’s a new record to the adapter though the record is updated before the polling cycle). So physical delete cannot capture UPDATED records.
    ii. Logical delete polling strategy: The logical delete polling strategy updates a special field of the table after processing each row (updates the where clause at runtime to filter out processed rows).The status column must be marked as processed after polling and the read value must be provided while configuring the adapter. Modified where clause and post-read values are handled automatically by the db adapter.
    Usage:
    <operation name="receive">
    <jca:operation
    ActivationSpec="oracle.tip.adapter.db.DBActivationSpec"
    PollingStrategyName="LogicalDeletePollingStrategy"
    MarkReadField="STATUS"
    MarkReadValue="PROCESSED"
    This polling strategy captures the updated records only if triggers are added.This is because when the record is polled, its status is updated to 'PROCESSED'. To capture this record if its updated, its status has to be 'UNPROCESSED'. So a trigger has to be added to update the status field to 'UNPROCESSED' whenever the record is updated. Below is the example.
    Ex:
    CREATE OR REPLACE TRIGGER nameOftrigger_modified
    BEFORE UPDATE ON table_name
    REFERENCING NEW AS modifiedRow
    FOR EACH ROW
    BEGIN
    *:modifiedRow.STATUS :='UNPROCESSED';*
    END;
    In this example, STATUS is the special field(of the polling table). When the record is updated, the trigger gets fired and updates the STATUS field to 'UNPROCESSED'. So when the table is polled, as this record's status is Unprocessed, this record ll be captured during polling.
    Other polling strategeis like "Sequencing Table Last Updated","Sequencing Table Last-Read Id" Polling strategy,etc also can be used to capture the updated records. In these strategies also, you need to add the triggers like the above. These need an extra helping table also to poll.
    Logical delete polling strategy is good enough to poll the updated records.
    Hope this helps.
    Thank you.

  • Create new rows or update rows in database table

    I have few table in database.
    I catch some values in my bean. Now I must put that values in my database tables. Values are in different tables.
    How can I update tables in database? Ok I know that my solution is updateable (entity) viewObject but please ... some example or description are welcome!
    Thx.
    Message was edited by:
    sinnerman

    Hi Frank. I read developer guide but this is detail and if you can help ... thanx in advance.
    I put code ... in my bean ... I need to insert row in table and commit. Please if you can answer me what`s wrong?
    code:
    FacesContext fc = FacesContext.getCurrentInstance();
    Application app = fc.getApplication();
    //Find corresponding object where variable "bindings" reside
    DCBindingContainer binding =
    (DCBindingContainer)app.getVariableResolver().resolveVariable(fc,
    "bindings");
    //Find the data control by name from the binding container
    DCDataControl dcCtl =
    binding.findDataControl("TMFStudServiceDataControl");
    //Retreive application module
    TMFStudServiceImpl am =
    (TMFStudServiceImpl)dcCtl.getApplicationModule();
    ViewObject vo = am.getGetIdStudentAnketaPitanje();
    ViewObject studentAnketaOdgovor = am.getStudentAnketaOdgovor();
    while (j < my_list.size()) {
    t = (Object)lista.get(j);
    System.out.println("IdOdgovora: " + t.toString());
    vo.setNamedWhereClauseParam("p_id_odgovora", t.toString());
    vo.executeQuery();
    Row currRow = vo.next();
    System.out.println("IdStudentAnketaPitanje: +currRow.getAttribute("IdStudentAnketaPitanje"));
    //am.insertStudentAnketaOdgovor();
    Row newStudentAnketaOdgovor = studentAnketaOdgovor.createRow();
    studentAnketaOdgovor.last();
    studentAnketaOdgovor.next();
    newStudentAnketaOdgovor.setAttribute("IdStudentAnketaPitanje", 1);
    newStudentAnketaOdgovor.setAttribute("IdOdgovor", 2);
    studentAnketaOdgovor.insertRow(newStudentAnketaOdgovor);
    am.getDBTransaction().commit();
    }

  • Database Adapter - Polling updated rows

    Hello, I have a question reguarding the polling strategy available in the database adapter.
    I set it up and it works great with new inserted rows in the table.
    However, it doesn´t capture the updated rows!
    For instance, i have the following table:
    ID - NAME - AGE
    1 -John- 21
    2 -Mary- 25
    When I insert a new row, it is captured by comparing the last captured ID in the sequencing file.
    ID - NAME - AGE
    1 -John- 21
    2 -Mary- 25
    3 -Cindy- 20 <--------- New row
    But when i UPDATE an already existing row, it doesnt load the changed row!
    ID - NAME - AGE
    1 -John- 26 <----------- Age changed, but polling doesnt recognize it!
    2 -Mary- 25
    3 -Cindy- 20
    Is there a way to get this to work? Should I set an special option? Thank you very much.
    Im using jdeveloper 11g.

    Hi John,
    I guess you're talking about BPEL? If so, try the BPEL forum for a better response.
    Best,
    John

  • ROW-00014: Cannot update row as the data in the database has changed

    We're having the problem below. We are trying to upgrade a 10g Oracle database via a linked server in SQL Server 2008.
    OLE DB provider "OraOLEDB.Oracle" for linked server "abc" returned message "ROW-00014: Cannot update row as the data in the database has changed".
    Mensagem 7343, Nível 16, Estado 4, Linha 1
    The OLE DB provider "OraOLEDB.Oracle" for linked server "abc" could not UPDATE table "[OraOLEDB.Oracle]".
    Can anyone help?
    Thank you.
    Edited by: user10641061 on 14/10/2011 18:48

    The columns that I want insert in oracle database have this data:
    JULIO DE SANT’ ANNA     KOLISNHG     1968-10-04 00:00:00.000     S     F     10     9     RUA, N° 999 / APT° 99999 RJ     TH     25410003     N°42.018      78550510     125296625     2178942326     2008-11-15 18:58:58.000
    Some of this data may be interfering with this insert?
    thank you
    Edited by: user10641061 on 15/10/2011 15:47
    Edited by: user10641061 on 15/10/2011 15:48

  • Updating Row in a Grid

    Hi All
        I m extracting data from SQL table onto xMII Dashboard using Grid template.I have one column named comments.
        I need that the supervisor using the Dashboard can change the comments as required and it should be reflected on the dashboard as well as It is updated in the database.
         Can anyone tell me how can I achieve this ? I am concerned whether I would be able to change an xMII Grid row ....
    Regards
    Amit

    Hi Amit,
    Add a cell selection event in your iGrid template definition
    e.g.
    <APPLET NAME="appDashBoard" WIDTH="100%" HEIGHT="250" CODE="iGrid" CODEBASE="/Illuminator/Classes" ARCHIVE="illum8.zip" MAYSCRIPT>
         <PARAM NAME="QueryTemplate" VALUE="/your/query/template">
         <PARAM NAME="DisplayTemplate" VALUE="/your/display/template">
         <PARAM NAME="InitialUpdate" VALUE="true">
         <PARAM NAME="CellSelectionEvent" VALUE="JavaScriptFunctionName">
    </APPLET>
    Create a query template to update new comment in database
    <APPLET NAME="appUpdateComment" WIDTH="1" HEIGHT="1" CODE="iCommand" CODEBASE="/Illuminator/Classes" ARCHIVE="illum8.zip" MAYSCRIPT>
    <PARAM NAME="QueryTemplate" VALUE="/update/comment">
    </APPLET>
    In your Java script function check whether the selected cell is part of the comment's column
    if (appDashBoard,getSelectedCellColumn() == 'Comment'){
       //capture new user comment
       var comment = prompt('Enter comment', '');
       //get record id from igrid for the selected comment
       var cellRow = appDashBoard.getSelectedCellRow();
       var rID = getCellValue(cellRow, columNumberOfID);
       var appUpdateCommentQry= appUpdateComment.getQueryObject(); 
       appUpdateCommentQry.setParam(1, rID);
       appUpdateCommentQry.setParam(2, comment );
       if(appUpdateComment.executeCommand()) {
       } else {
       appDashBoard.updateGrid(true);

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

  • ExecuteBatch(): number of successfully updated rows

    Hello everybody:
    Here is a simple but often a repeated question in java forums:
    Requirement:
    1.To read a flat file that has many rows of data.
    2.Parse the data and update the database accordingly.
    3.Find the number of successfully updated rows.
    Approach:
    After reading the file and parsing its data,
    - use PreparedStatement
    - use executeBatch()
    I found this as unadvisable to use executeBatch() as its implementation is
    inherently driver specific. The executeBatch() returns an array of update counts.
    Now,can any one tell me, what is the best way to trace the number of successfully
    (and unsuccessfully) updated rows by using this count?
    Is there any other way to achieve the same by not using executeBatch()?
    Can any one share a snippet of code to achieve this specific functionality?
    [Need is to log the number of unsuccessful attempts along with their
    corresponding rows of data].
    Thanks & regards,
    Venkat Kosigi

    executeBatch submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts. The int elements of the array that is returned are ordered to correspond to the commands in the batch, which are ordered according to the order in which they were added to the batch. The elements in the array returned by the method executeBatch may be one of the following:
    -- A number greater than or equal to zero indicates that the command was processed successfully and is an update count giving the number of rows in the database that were affected by the command's execution
    -- A value of -2 indicates that the command was processed successfully but that the number of rows affected is unknown
    If one of the commands in a batch update fails to execute properly, this method throws a BatchUpdateException, and a JDBC driver may or may not continue to process the remaining commands in the batch. However, the driver's behavior must be consistent with a particular DBMS, either always continuing to process commands or never continuing to process commands.
    If the driver continues processing after a failure, the array returned by the method BatchUpdateException.getUpdateCounts will contain as many elements as there are commands in the batch, and at least one of the elements will be the following:
    -- A value of -3 indicates that the command failed to execute successfully and occurs only if a driver continues to process commands after a command fails.
    return values have been modified in the Java 2 SDK, Standard Edition, version 1.3 to accommodate the option of continuing to proccess commands in a batch update after a BatchUpdateException obejct has been thrown.
    Throws BatchUpdateException (a subclass of SQLException) if one of the commands sent to the database fails to execute properly or attempts to return a result set. The BatchUpdateException getUpdateCounts() method allows you to known the element who caused the fail identified by a -3 value.
    -- So, if you have a succesfully result, look for at the executeBatch returned array ( #values >= 0 ) + ( #values == -2 ) = successes
    and if you have not a succesfully result, catching the BatchUpdateException take the array returned by the getUpdateCounts() method, and look for the position in which array values are -3. You could take the data at this position on batch and log it.
    -- Other way to insert a bulk copy on database is to use a bcp command ( it�s not java, bcp is an independent command ) that allows you to do bulk inserts from file, indicate an error file, bcp will give to you as result a file with those lines not where inserted.
    I hope have help you.;)

  • The updated row cannot be refreshed because its key values are unset ERROR

    Hi
    Doing commit operation with adf business components on mysql database. The moment i have inserted a new record into the table i need to get the value of the primary key column for that inserted row.How to get the value of the primary key column.i set refresh on insert and refresh on update properties in the corresponding EO. then iam getting The updated row cannot be refreshed because its key values are unset or modified by database triggers. error.Suggest how to resolve this error and how to achieve this functionality.
    Thanks
    Satya

    Here the primary key column is auto_increment column in database table.

  • View Data & Updating row count

    Hi,
    iam using OBIEE 11g, when iam importing data from sysbase into physical layer then in the physical layer i cant able to view data and update row count also.
    For sysbase which dataconnection we have to use i.e (ODBC 3.5, OCI 10g/11g).
    for ODBC 3.5 connection is established but we cant get data i.e (view data in Physical layer ), for OCI 11g we cant establish a connection.
    Thanks in advance.
    prakash

    Hi,
    *• Relational Database System* including Oracle Database, Oracle Exadata Database Machine, Oracle TimesTen In Memory Database, DB2, Microsoft SQL Server, Teradata, Netezza, Informix, Sybase and other ODBC compliant data sources
    *• OLAP Sources* including Oracle Essbase, Hyperion Financial Management, Oracle Database OLAP Services, Oracle RPAS, Microsoft Analysis Services Cubes, and SAP BW Infocubes.
    *• XML Data Sources* including access to other types of data servers (e.g., other non-relational servers), Microsoft Excel spreadsheets, and Web Services.
    So, we should use ODBC 3.5 as Call Interface for Sybase.
    Thanks,
    Balaa...

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

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

  • Obiee oracle gateway error while updating row count

    Hi ,
    OBIEE server 11.1.1.5 ,oracle server11g installed in linux 64bit,
    while updating row count in Admin tool i am getting the following error
    [NQODBC][SQL_STATE:HY000][nQSError:10058] A general error has occured.
    [nQSError: 43113]Message returned from OBIS.
    [nQSError:43093]An error occured while processing the EXECUTE PHYSICAL statement.
    [nQSError:17003]Oracle gateway error: OCIEnvNIsCreate or OCIEnvInit failed to initialize environment.Please check your Oracle Client installation and make sure the correct version of OCI libraries are in the library path.
    i am able to check the database from sqlplus it is working fine.
    Any suggestion highly appreciated plzzz

    Make sure your connection pool is valid and able to import or execute reports.
    If everything good as above said, in Physical layer database properties-> general tab choose the database version and try it once.
    If not
    Check the doc id 1271486.1
    Or
    To resolve the issue create a softlink (ln -s) in the <OracleBI>/server/Bin folder to link to the 32-bit Oracle Client Driver file.
    The example below shows how to perform a softlink from the 64 bit directory:
    cd /u10/app/orcladmin/oracle/OracleBI/server/Bin
    ln -s $ORACLE_HOME/lib32/libclntsh.so.10.1 libclntsh.so.10.1
    If helps mark

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

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

Maybe you are looking for

  • Converting carriage return in HTML spool

    I've written an sql for spooling the result of a Select in HTML format by using "set markup html on spool on head". The problem is that when I open the HTML file I no longer find the carriage returns. I mean the carriage returns that were in CLOB fie

  • Is Response Required in Proxy Service and Business Service

    Hi All, I have made proxy service that is putting message on the Queue through a Business Service. Now I wanted to know what is the use of "Is Response Required" configuration parameter in Business as well Proxy Service. Also what is the significance

  • Having problems updating Photoshop CS6 to version 13.0.5?

    What is causing problem updating Photoshop CS6 13.0 x64 Extended to version 13.0.5 (Error Code U44M2P7) on Mac running OS X 10.8,4? What is the solution? (I tried to post this question on the Photoshop forum but was denied. What could cause this?)

  • Appleworks 6 Documents to Pages on OS 10.7

    I have a Mac Mini running OS 10.7.2, with an installed copy of Pages 09. From my previous Mac (OS 10.3) I have many word processing documents created on Appleworks 6. I should be able to open these documents using Pages, according to all the experts.

  • Canon MP 700 - problems printing from Leopard

    I have a Canon MP 700 printer and was using it happily until I upgraded to Leopard. I visited a whole bunch of forums in search of a solution and tried to "trick" my MacBook into printing by attempting to piggy back ride on other Canon drivers, but n