Updating TABLEA based on values in TABLEB

Hi: I have the two following tables. I want to write a query which updates fields in TABLE1 based on certain values in TABLE2
1. Update SEVERITY in TABLE1 with SVRT_CD in TABLE2 for all TABLE1.INCIDENT = TABLE2.TKT_NBR
2. Update ESCALATION in TABLE1 with ESCL_LVL in TABLE2 for all TABLE1.INCIDENT = TABLE2.TKT_NBR
3. If the TABLE2.MNS_STATUS is 5 then set TABLE1.INCIDENTSTATUS='Acls' for all TABLE1.INCIDENT = TABLE2.TKT_NBR
4. If the TABLE2.MNS_STATUS is 4 then set TABLE1.INCIDENTSTATUS='Bctk' for all TABLE1.INCIDENT = TABLE2.TKT_NBR
remedy@MDS> descr TABLE1;
USERID         NOT NULL VARCHAR2(32)
INCIDENT       NOT NULL VARCHAR2(64)
INCIDENTSTATUS NULL     VARCHAR2(16)
SEVERITY       NULL     NUMBER
ESCALATION     NULL     NUMBER
ONSTRAINT user_pk PRIMARY KEY (USERID,INCIDENT)
netcool@RMDSP02> describe TABLE2;
TKT_NBR                     NULL     NUMBER(10,0)
ESCL_LVL                    NULL     NUMBER(2,0)
SVRT_CD                     NULL     VARCHAR2(1)
MNS_STATUS                  NULL     NUMBER(1,0)
CONSTRAINT tkt_pk PRIMARY KEY (TKT_NBR)I think this will do what I want in #1 and #2. Can someone confirm?
UPDATE TABLE1
SET (SEVERITY, ESCALATION) = (SELECT SVRT_CD,ESCL_LVL from TABLE2 where to_number(TABLE1.INCIDENT) = TABLE2.TKT_NBR)Not sure how do I do the #3 and #4.
Thanks
Ravi

For point 3 and 4 use decode. and dont forget to use EXISTS in your update.
UPDATE table1
   SET (severity,
        escalation,
        incidentstatus) = (SELECT svrt_cd,
                            escl_lvl,
                            DECODE(mns_status,5,'Acls',4,'Bctk')
                       FROM table2
                      WHERE TO_NUMBER(table1.incident) = TABLE2.TKT_NBR)
WHERE EXISTS (SELECT NULL
              FROM table2
             WHERE TO_NUMBER(table1.incident) = TABLE2.TKT_NBR)        Thanks,
Karthick.

Similar Messages

  • Update table based on values from other table

    Hi,
    I am trying to update one table based on the values of another table. Since you can't use From in update statements, how do you execute this?
    For example i have to tables, Table A and Table B. I want to update a column or columns in Table A based on another value in Table B:
    So if the column in Table B was 1 then column in Table A would be Yes, if Table B was 2, then Table A would be Yes, if Table B was 3 then Table A would be N/A and so on...
    Any help would be appreciated.
    thanks,
    scott

    SQL> select * from t1;
    ID ST
    1
    2
    3
    SQL> select * from t2;
    NO
    1
    2
    3
    4
    SQL> update t1 set status=(select decode(no,1,'Y',2,'N','NA') from t2 where t1.id=t2.no);
    3 rows updated.
    SQL> select * from t1;
    ID ST
    1 Y
    2 N
    3 NA
    Daljit Singh

  • Deleting from a table based on values in a second table

    Is it possible to DELETE from (or for that matter do an UPDATE to) a table based on values in another table? I have gone through the online documentation but can't seem to find anything. I'm trying to delete rows from table A where A.field1 = B.field1 and B.field2 = 'X'. (B being the second table)

    It is done using subqueries in the where clause.
    delete from A
    where A.field1 in (select B.field1 from B where B.field2 = 'X');
    delete from A
    where exists (select 'x' from B where B.field1 = A.field1 and B.field2 = 'X');
    delete from A
    where A.rowid in (select A.ROWID from from A, B where B.field1 = A.field1 and B.field2 = 'X');
    And many other varieties. Eg. more specialised:
    delete from A
    where A.txdate < (select B.prune_date FROM B where B.field1 = A.field1 and B.field2 = 'X')
    and A.txstate in (select S.txstate from S where S.prodlass=a.prodclass and s.deletable='Y');

  • Deleting rows from table based on value from other table

    Hello Members,
    I am struck to solve the issue said below using query. Would appreciate any suggestions...
    I have two tables having same structures. I want to delete the rows from TableA ( master table ) with the values from TableB ( subset of TableA). The idea is to remove the duplicate values from tableA. The data to be removed are present in TableB. Catch here is TableB holds one row less than TableA, for example
    Table A
    Name Value
    Test 1
    Test 1
    Test 1
    Hello 2
    Good 3
    TableB
    Name Value
    Test 1
    Test 1
    The goal here is to remove the two entries from TableB ('Test') from TableA, finally leaving TableA as
    Table A
    Name Value
    Test 1
    Hello 2
    Good 3
    I tried below queries
    1. delete from TestA a where rowid = any (select rowid from TESTA b where b.Name = a.Name and a.Name in ( select Name from TestB ));
    Any suggestions..
    We need TableB. The problem I mentioned above is part of process. TableB contains the duplicate values which should be deleted from TableA. So that we know what all values we have deleted from TableA. On deleted TableA if I later insert the value from TableB I should be getting the original TableA...
    Thanks in advance

    drop table table_a;
    drop table table_b;
    create table  table_b as
    select 'Test' name, 1 value from dual union all
    select 'Test' ,1 from dual;
    create table table_a as
    select 'Test' name, 1 value from dual union all
    select 'Test' ,1 from dual union all
    select 'Test' ,1 from dual union all
    select 'Hello' ,2 from dual union all
    select 'Good', 3 from dual;
    /* Formatted on 11/23/2011 1:53:12 PM (QP5 v5.149.1003.31008) */
    DELETE FROM table_a
          WHERE ROWID IN (SELECT rid
                            FROM (SELECT ROWID rid,
                                         ROW_NUMBER ()
                                         OVER (PARTITION BY name, VALUE
                                               ORDER BY NULL)
                                            rn
                                    FROM table_a a
                                   WHERE EXISTS
                                            (SELECT 1
                                               FROM table_b b
                                              WHERE a.name = b.name
                                                    AND a.VALUE = b.VALUE))
                           WHERE rn > 1);
    select * from table_a
    NAME     VALUE
    Test     1
    Hello     2
    Good     3Edited by: pollywog on Nov 23, 2011 1:55 PM

  • Update table all null values to 0 single query

    hi dear ;
    How Can I do , update table all null values to 0 using single query or procedure

    declare @tableName nvarchar(100)
    declare @querys varchar(max)
    set @querys = ''
    set @tableName = 'YOUR TABLE NAME HERE'
    select @querys = @querys + 'update ' + @tableName + ' set ' +
    QUOTENAME(t.[name]) + '=0 where ' + QUOTENAME(t.[name]) + ' is null;'
    from (SELECT [name] FROM syscolumns
    WHERE id = (SELECT id
    FROM sysobjects
    WHERE type = 'U'
    AND [NAME] = @tableName))t
    select @querys
    execute sp_executesql @sqlQuery
    Reference:
    http://stackoverflow.com/questions/6130133/sql-server-update-all-null-field-as-0
    -Vaibhav Chaudhari
    this code is return update TABLE set [FIELD]=isnull([FIELD],''),update TABLE set [FIELD2]=isnull([FIELD2],'')
    I want to use UPDATE TABLE SET FIELD1=ISNULL(FIELD1,0),FIELD2=ISNULL(FIELD2,0),FIELD3=ISNULL(FIELD3,0)  So CUT another update and set statement .

  • Update table based on ID reference comparing each column and value

    Hi,
    Through UI user can update any information and click save. In backend i will be receiving only ID as reference . Based on the ID value i should update multiple tables wherever i have the reference tables. Here i will not get the values or column name updated.
    I just get a ID to find which row is updated.
    I should do a comparision now. 
    I have a history table where i get the row before updation. and i get a row after updation from current data i.e. from ssdb_Railroad[This will be updated by java after updation we will get the ID inorder to update remaining tables]. Now i need to compare
    both the table column values and know which column is updated and after getting the value i should update reference tables.
    Below is the structure for comparision table , History table and Main table.
    Create table Comparision_History (
     ID   int IDENTITY(1,1) PRIMARY KEY,
     InsertUser_UpdateUser varchar(50),
     Old_ColVal  varchar(100),
     New_ColVal  varchar(100),
     TableName   varchar(100),
     [Action]     varchar(50),
     InsertDate_UpdateDate Datetime NOT NULL DEFAULT getdate()
    CREATE TABLE SSDB_Railroad_History (
        ID         int IDENTITY PRIMARY KEY,
    SCAC       varchar(4) ,
    Name       varchar(50) NOT NULL,
    RailroadID int NOT NULL UNIQUE,
    RC2Key
      varchar(50),
    NOTES      varchar(1000),
    [Action]   varchar(50),
    InsertDate_UpdateDate  Datetime NOT NULL DEFAULT getdate(),
    InsertUser_UpdateUser  varchar(50),
    CREATE TABLE SSDB_Railroad (
        ID   int IDENTITY(1,1)PRIMARY KEY,
    SCAC varchar(4) UNIQUE,
    Name varchar(50) NOT NULL,
    RailroadID int NOT NULL UNIQUE,
    RC2Key
    varchar(50),
    InsertDate Datetime NOT NULL DEFAULT getdate(),
    UpdateDate Datetime,
    InsertUser varchar(50),
    UpdateUser varchar(50)
    Here SSDB_Railroad table and History table needs to be compared and get a updated value and it should be inserted in a comparision table. as well as it should be updated in reference tables.
    Please help me with the code.
    Thanks in Advance
    Deepa

    Hi Deepa_Deepu,
    According to your description, personally, the merge function can meet your requirements. Usually, we can synchronize two tables by updating or inserting rows in a target table based on differences found in the source tables. Just as your description, when
    the value of ID and InsertDate_UpdateDate in the source table matches a value, update them in the target table. When the values does not match, the source row is inserted into the target table.
    For more information, see: using MERGE to perform UPDATE and INSERT operations on a target table by using a derived source table.
    http://msdn.microsoft.com/zh-cn/library/bb510625.aspx
    Regards,
    Sofiya Li
    Sofiya Li
    TechNet Community Support

  • Error updating tables based on schema

    Hello,
    I'm trying to update a table based on the next schema:
    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xdb="http://xmlns.oracle.com/xdb" xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
         <xs:element name="HILO" xdb:SQLType="HILO_TYPE" xdb:defaultTable="HILO_TABLE">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="MENSAJE" maxOccurs="unbounded" xdb:SQLType="MENSAJE_TYPE" xdb:maintainOrder="false">
                             <xs:complexType>
                                  <xs:sequence>
                                       <xs:element name="FECHA" type="xs:date" xdb:SQLType="DATE"/>
                                       <xs:element name="TITULO" xdb:SQLType="VARCHAR2">
                                            <xs:simpleType>
                                                 <xs:restriction base="xs:string">
                                                      <xs:maxLength value="200"/>
                                                 </xs:restriction>
                                            </xs:simpleType>
                                       </xs:element>
                                       <xs:element name="CUERPO" type="xs:string" xdb:SQLType="VARCHAR2"/>
                                       <xs:element name="DNI_CREADO_POR" xdb:SQLType="VARCHAR2">
                                            <xs:simpleType>
                                                 <xs:restriction base="xs:string">
                                                      <xs:maxLength value="9"/>
                                                 </xs:restriction>
                                            </xs:simpleType>
                                       </xs:element>
                                       <xs:element name="ASIGNATURA" xdb:SQLType="VARCHAR2">
                                            <xs:simpleType>
                                                 <xs:restriction base="xs:string">
                                                      <xs:maxLength value="3"/>
                                                 </xs:restriction>
                                            </xs:simpleType>
                                       </xs:element>
    <xs:element name="APROBADO" xdb:SQLType="VARCHAR2">
    <xs:simpleType>
    <xs:restriction base="xs:string">
    <xs:enumeration value="APROBADO"/>
    <xs:enumeration value="RECHAZADO"/>
    <xs:enumeration value="PENDIENTE"/>
    </xs:restriction>
    </xs:simpleType>
                                       </xs:element>
                                  </xs:sequence>
                                  <xs:attribute name="NUMERO" type="xs:int" use="required" xdb:SQLType="INTEGER"/>
                             </xs:complexType>
                        </xs:element>
                   </xs:sequence>
                   <xs:attribute name="CONTADOR" type="xs:int" use="required" xdb:SQLType="INTEGER"/>
              </xs:complexType>
         </xs:element>
    </xs:schema>
    And the update that i'm trying to do is the next one:
    UPDATE hilo_table p
    SET value(p) =
    updatexml(value(p),'/HILO/MENSAJE/CUERPO/text()', 'Edit' )
    where existsnode(VALUE(p), 'HILO[@CONTADOR="1"]') = 1;
    ERROR en línea 1:
    ORA-01732: operación de manipulación de datos no válida en esta vista
    I have updated another tables based on schema and it works fine, any idea?

    OK this is your decision. However If you are building a production system that is important to your orgnanization as the product manager I strongly recommend that you either upgrade to a least 9.2.0.3.0 or discontinue using XML DB technology completely
    There are probably somewhere in the order of 500 serious XML DB related bugs fixed between 9.2.0.1.0 and 9.2.0.7.0, all of which have been regarded as serious enough to impossible for a customer to develop or deploy a production system. None of these will EVER be fixed or available as patches for 9.2.0.1.0.
    The way in which we store the data on the disc is different in 9.2.0.3.0, and while in theory we migrate the on disc format when you upgrade in practice I know that is has never been tested with any significant amount of data present.
    Also you really want to take the support situation into account. Image this, it's 3:00am in the morning and your production system fails due one of the bugs that have been fixed in a later release of the product. You cannot find a workaround and you call oracle support for help. They WILL say, sorry there is nothing we can do until you upgrade to 9.2.0.3.0. Now you have to upgrade in hurry and then re-test everything you have done before you can even start working on a fix.
    From a business perspective staying on 9.2.0.1.0 and continuing to use the XML DB technology makes no sense. I hope I have made this clear. If you want I will be more than happy to discuss this issue with your development managers.

  • Update table based on collection

    Hello friends,
    I have two tables:
    1- PHOTOS (img_id number (5,0),Product_id number (5,0), Content Blob ....)
    2- PRODUCTS (Product_id number (5,0), product_type .... )
    each product has 1 to 6 images.
    I need to watermark the uploaded images in the memory then update the original images for the watermarked images.
    I used this code, but the problem is how to update the images in the photos table based on the product_id ???
    DECLARE
    type source_col is table of blob index by pls_integer ;
    V_source source_col;
    cursor c1 is select CONTENT from photos where Product_id = :P22_Product_id;
    counter number :=1;
    added_image       BLOB;
    prop ordsys.ord_str_list;
      logging VARCHAR2(2000);
    begin
    --- Here we choose a pattern for watermarking from a table called WATERMARK_PHOTOS
    select img INTO added_image FROM WATERMARK_PHOTOS WHERE N = 1;
    for rec in c1 loop
    V_source(counter) := rec.CONTENT;
    ORDSYS.ORDImage.process(V_source(counter), 'fixedScale=900 500');
    ORDSYS.ORDImage.applyWatermark(V_source(counter), added_image, V_source(counter), logging, prop);
    --- The problem in the following statement: How to update the images
    UPDATE photos SET CONTENT = V_source(counter) where Product_id = :P22_Product_id;
    Counter := counter + 1 ;
    end loop;
    COMMIT;
    EXCEPTION
       WHEN OTHERS THEN
       RAISE;
    END;

    Thanks Sybrand,
    I am using Oracle 11g R2 Standard One edition.
    the DDL of the photos table is
    ID     NUMBER     5     0     
    product_id     NUMBER     5     0     
    FILENAME     VARCHAR2     100          
    MIMTYPE     VARCHAR2     250          
    FILESIZE     VARCHAR2     20          
    CONTENT     BLOB          in my application I do not know the image id in advance, but i know the id of the product of which I want to edit the images. So:
    in the following procedure :p22_product_id is the value of of the primary key of Products table.
    I followed your tips, and it worked out. Can you please check and assure that it is OK :
    DECLARE
    type source_col is table of blob index by pls_integer ;
    V_source source_col;
    type id_col is table of number index by pls_integer ;
    V_id id_col;
    added_image       BLOB;
    prop ordsys.ord_str_list;
      logging VARCHAR2(2000);
    begin
    select content bulk collect into V_source from photos where product_id = :p22_product_id order by id ;
    select id bulk collect into V_id from photos where product_id = :p22_product_id order by id ;
    SELECT img INTO added_image FROM timg WHERE N = 1;
    for i in V_source.first .. V_source.last
    loop
    ORDSYS.ORDImage.process(V_source(i), 'fixedScale=900 500');
    ORDSYS.ORDImage.applyWatermark(V_source(i), added_image, V_source(i), logging, prop);
    UPDATE photos SET CONTENT = V_source(i) where id = V_id(i);
    end loop;
    COMMIT;
    EXCEPTION
       WHEN OTHERS THEN
       RAISE;
    END;Best Regards,
    Fateh

  • Select from different tables based on value

    Hi Forum,
    I'm stuggling with a problem:
    In a table, I have two columns, pref_type and pref_value. Column pref_type stores a number value that is linked to a preference type, whereas column pref_value stores the value of that preference.
    Unfortunately, the data model is such that per preference type a different tables needs to be used, so for example, if
    pref_type = 1, table to query is A, whereas if
    pref_type = 2, table to query is B.
    I now want to write a query that resolves the preferences, ie it should branch to the respective table based on pref_type and search for pref_value and deliver back a different column of that respective table.
    My first approach was like that:
    select decode (pref_value, 1, (select result from A where pref_value = ???),
    2, (select result from B where pref_value = ???)
    where the three ??? depict the problem I'm having, as Oracle doesn't allow me to have a harmonized subquery here.
    How do I achieve this?
    Thanks for any help,
    J. Sieben

    I believe this is what you are trying to get at:
    SELECT DECODE(m.pref_type, 1, (SELECT result FROM a
                                   WHERE a.pref_value = m.pref_value),
                               2, (SELECT result FROM b
                                   WHERE b.pref_value = m.pref_value)
    FROM my_table mAlthough, if the tables are large, that might be pretty slow. Better than an outer join, but one of those correlated queries is going to be run for each row in my_table. You could lso try something like:
    SELECT m.pref_type, r.result
    FROM my_table m,
         (SELECT 'A' tbl, pref_value, result
          FROM a
          UNION ALL
          SELECT 'B', pref_value, result
          FROM b) r
    WHERE DECODE(m.pref_type, 1, 'A', 'B') = r.tbl and
          m.pref_value = r.pref_valueHTH
    John

  • Update column based on values of same table

    I have table T1 with 4 columns 'col1','col2','col3','col4', 'col5','col6' as follows
    Col1     Col2     Col3     Col4     Col5     Col6
    1111     City1     C     AA     DDD     A1
    2222     City 1          DD     HHH     A1
    3333     City2     B     EE     OOO     
    4444     City 1     B     JJ     SSS     A1
    5555     City2     C     KK     VVV     
    6666     City2          RR     QQQ     
    7777     City2     B     XX     BBB     
    I have already updated Column 6with value ‘A1’ where Column 2 is ‘City1’.
    Now I want to update col 6 where col2 is ‘S’ with following conditions
    If Col 3 = ‘B’ then Col6 should be = col4
    else it should be = col5

    SET col6=DECODE(col3,'B',col4,col5)
    WHERE col2='S'

  • Update vs Merge - Updating one table based on values in another

    Hello
    I have two tables lets say TAB_A and TAB_B. I altered table B to include a new column from table A
    I wrote a merge statement as follows to merge the data
    MERGE INTO TAB_A
    USING TAB_B
    ON (TAB_A.SECURITYPERSONKEY=TAB_B.SECURITYPERSONKEY)
    WHEN MATCHED THEN
      UPDATE SET TAB_A.PPYACCOUNT=TAB_B.PPYACCOUNT;
    I know INSERT is for inserting new records
    UPDATE to my knowledge is to modify currently existing records (loosely)
    MERGE is one I rarely used, until this particular scenario.
    The code works perfectly fine, but I was wondering how could I write an update statement? Or in this scenario should I even be using an update statement?

    The MERGE is good and performs well, although it malfunctions (sometimes updating data wrongly) if the destination is a view with INSTEAD OF triggers.
    The UPDATE with similar performance to the MERGE depends on SECURITYPERSONKEY being a unique or primary key on TAB_B. It is:
    update (select TAB_A.PPYACCOUNT a_PPYACCOUNT, TAB_B.PPYACCOUNT b_PPYACCOUNT
            from TAB_A JOIN TAB_B on TAB_A.SECURITYPERSONKEY=TAB_B.SECURITYPERSONKEY)
    SET A_PPYACCOUNT=B_PPYACCOUNT;
    This can set multiple columns. It also currently doesn't work on a view with INSTEAD OF triggers.
    Frank's update also works with multiple columns (eg also updating col2 and col2), with this syntax:
    UPDATE  tab_a
    SET     (ppyaccount, col2, col3) = (
                             SELECT  ppyaccount, col2, col3
                             FROM   tab_b
                             WHERE  securitypersonkey  = tab_a.securitypersonkey
    WHERE   EXISTS       (
                             SELECT  ppyaccount
                             FROM    tab_b
                             WHERE   securitypersonkey  = tab_a.securitypersonkey

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

  • Calling functions and inserting tables based on values entered

    Hello Everyone,
    I am creating a function as below:
    create or replace function func(flags in number,Ctry in varchar2) return number
    is
    maxv number;
    flagv number;
    begin
    flagv:=1;
    select max(num) into maxv from A;
    if flags =1 then
    insert into A(num,nam) values(maxv+1,Upper(Ctry));
    else
    flagv:=0;
    end if;
    return flagv;
    end;
    The function takes two parameters-The first one will be either 0 or 1.The second one will be name of a country.
    If the first parameter is 1 then we would insert the country name passed, to the table name A.If its 0 then no insertion occurs and the function would return a value 0.
    On compiling the function I get a success!.
    When I do a
    SQL>select distinct func(0,'UK') from B;
    it works well and returns 0
    However when I do
    SQL>select distinct func(1,'UK') from B;
    I expect an output of 1 & also expect UK to be inserted as anew row in the table A.However It throws an error saying "ORA-14551: cannot perform a DML operation inside a query .."
    It is very important for me to use select to call the function, as my application would fire a select with that function and based on the value entered would insert or not insert at the back end.
    Is there any way out to do this??
    variable temps number
    exec :number :=func(1,'UK');
    does work but I cant use this in my application.
    Hope you can help! Thanks!

    create or replace function func(flags in number,Ctry in varchar2) return number
    is
    PRAGMA AUTONOMOUS_TRANSACTION;
    maxv number;
    flagv number;
    begin
    flagv:=1;
    select max(num) into maxv from A;
    if flags =1 then
    insert into A(num,nam) values(maxv+1,Upper(Ctry));
    COMMIT;
    else
    flagv:=0;
    end if;
    return flagv;
    end;
    Is the above changes in BOLD enough or I need to do something else too in order to incorporate the autonomous transaction??
    I am not too familiar with autonomous transaction.Could you please suggest the changes I need if any more required??
    Thanks a ton for your suggestions!
    Message was edited by:
    user579245
    Message was edited by:
    user579245

  • Trying to update table based on combo box choice

    Hey all,
    I have taken over code someone has created and it is confusing me what they have done. the code uses an abstracttablemodel to create the table (and i assume, fill the data). I can't for the life of me, figure out how the data is loaded. Can someone tell me what is happening. also, what would be the easiest way to update it to only show that info that matches the criteria? I will post what i think is relevant code, but if i am missing something, i will be happy to throw it in there. Here's the code:
    public class ABMD extends JPanel implements ActionListener
    private JTable table;
        private TableSorter sorter;
    public ABMD()
    sorter = new TableSorter(new ABMDTableModel());
            table = new JTable(sorter);
            sorter.setTableHeader(table.getTableHeader());
            ListSelectionModel rowSM = table.getSelectionModel();
            rowSM.addListSelectionListener(new ListSelectionListener()
                public void valueChanged(ListSelectionEvent e)
                    if (e.getValueIsAdjusting()) return;
                    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                    if (lsm.isSelectionEmpty())
                        viewDataButton.setEnabled(false);
                        getDataButton.setEnabled(false);
                        removeDataButton.setEnabled(false);
                    else
                        int selectedRow = sorter.modelIndex(table.getSelectedRow());
                        PlanData currentPlanData = (PlanData) planArrayList.get(selectedRow);
                        if (!currentPlanData.getPlanListLoaded())
                            getDataButton.setEnabled(true);
                            viewDataButton.setEnabled(false);
                            removeDataButton.setEnabled(false);
                        else
                            getDataButton.setEnabled(false);
                            viewDataButton.setEnabled(true);
                            removeDataButton.setEnabled(true);
                        String desc = "";
                        desc = currentPlanData.getUniqueID();
                        descTextAreaValue.setText(desc);
    class ABMDTableModel extends AbstractTableModel
            private String[] columnNames = {"Plan Local",
                    "OPLAN",
                    "Air Defense Plan",
                    "Planning Period",
                    "Defense Design",
                    "Published Date"
            public int getColumnCount()
                return columnNames.length;
            public int getRowCount()
                return planArrayList.size();
            public String getColumnName(int col)
                return columnNames[col];
            public Object getValueAt(int row, int col)
                PlanData planData = (PlanData) planArrayList.get(row);
                switch(col)
                    case 0:
                        return Boolean.valueOf(planData.getPlanListLoaded());
                    case 1:
                        return planData.getOplan();
                    case 2:
                        return planData.getAirDefensePlan();
                    case 3:
                        return planData.getPlanningPeriod();
                    case 4:
                        return planData.getDefenseDesign();
                    case 5:
                        return planData.getPublishedDate();
                throw new IllegalArgumentException("Illegal Column: " + getColumnName(col));
            public Class getColumnClass(int c)
                return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col)
                return false;
    }

    I can't for the life of me, figure out how the data is loadedLooking at the get value method we see:
    PlanData planData = (PlanData) planArrayList.get(row);Therefore the data is store in the "planArrayList". So the data is loaded whenever you add data to that ArrayList.

  • How to dynamically and selectively update DSO based on values in a csv file

    Hi,
    I'm loading a csv file into a DSO. When loading the flat file in FULL mode I need to do a pseudo delete of records that were previously loaded but are not in the new flat file.
    Is it possible to dynamically determine the unique set of records (say Pk1, Pk2, Pk3) in the csv file and then set all the corresponding DSO records' quantities to 0 - maybe in a start routine??  After that, I can load the csv file with the correct quantities (effectively update and inserts).  The net result should be that the change log only be updated through to the next DSO.
    Example: Load 10 records yesterday. Today reload 9 records. 10th records must have quantity set to 0. Other 9 records will have quantity values set to those in today's csv file -  some will be the same & some will be different. The net change log of all 10 records must be loaded into the next DSO.
    Any suggestions on how to do this logic?
    Thanks!

    Hi Gregg,
    You can create one transformation from the DataStore to itself.  In the "Technical" rules group, set 0RECORDMODE = 'X' (before image) or 'R' (reverse).  Therefore, when you execute its corresponding DTP, all existing records shouldl be set to zero.
    Then, as a second step, you can execute the DTP which is related to the transformation between the DataStore and the DataSource, thus loading the new records.
    I hope this helps you.
    Regards,
    Maximiliano

Maybe you are looking for

  • Unable to create archive. please help!

    hello everyone, i am trying to archive a project into a new folder using the media manager. the project bin contained many different sequences and was "saved as" many times in different names. when i reached the final version of the project i wanted

  • Is there a known issue displaying pages?

    Using Adobe Digital Editions version 3.0.86137, I can only view one page each time I "read" a document. PageUp and PageDown will change the page number shown at the bottom of the reader screen, but the page content does not change. The only way I hav

  • How to create a navibar and gear(spinner) programatically in cocoa view app

    Hi All, How to create a navigation bar and gear(spinner) programmatic ally in cocoa view based application. In navigation bar just i need to display Application Title.

  • Verify/Repair disk permissions

    I heard that it's a good idea to verify and repair disk permissions. What does that do? And, when should I do it? -Eric

  • UNCAUGHT_EXCEPTION message when creating a Shopping Cart

    Hi All, I would appreciate it if someone could provide an insight to the error message below. It occurs when the user attemps to enter a text decription shopping cart. I have checked the org structure set-up and attributes but am at a loss to to find