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

Similar Messages

  • How to suppress a row based on current date -  at query level?

    In an Bex query report i have suppress rows based on current date.
    There is no current date available in query.
    there is a date field in the query.
    If by chance the date in that field is lesser than current date, I have to suppress that row.
    How can this be achieved?

    What is the code ofr creating a variable to get values >= to current date?
    I have implemented the following code which is not working.
    data L_S_range like line of E_T_range[].
    CLEAR L_S_RANGE.
    L_S_RANGE-SIGN = 'I'.
    L_S_RANGE-OPT = 'GE'.
    L_S_RANGE-LOW = SY-DATUM.
    APPEND L_S_RANGE TO E_T_RANGE[].
    Actually i have written in class, which will be inherited in superclass.
    Edited by: akshara20 on Feb 2, 2011 1:21 PM

  • How can I select and delete rows based on the value in one column?

    I searched through the discussion board, and found a thread on deleting blank rows, but not sure how to modify it to work with my issue.
    I have put together a rather complicated spreadsheet for designing control systems, it calculates parts needed based on check boxes selected in a second spreadsheet.
    Since not all systems require all parts there are many rows that have a 0 quantity value, I would like to select these rows and delete them once I have gone through the design phase (checking off required features on a separate sheet).
    I like the way the other thread I found will gather all the blank rows at the bottom without changing the order of the rows with data in them.
    I don't understand exactly how the formula in the other thread works well enough to modify it to look for a certain column.
    I hope I made myself clear enough here, to recap, I would like to sort the rows based on a zero value in one (quantity) column, move them (the zero quantity rows) to the bottom of the sheet, and then delete the rows with a zero quantity (I can delete them manually, but would like to automate the sorting part).
    Thanks for any help anyone can provide here.
    Danny

    I apologize but, as far as I know, Numbers wasn't designed by Ian Flemming.
    There is no "this column will be auto-destructing after two minutes"
    You will have to use your fingers to delete it.
    I wish to add a last comment :
    if your boss has the bad habit to look over your shoulder, it's time to find an other one.
    As I am really pig headed, it's what I did. I became my own boss so nobody looked over my shoulder.
    Yvan KOENIG (VALLAURIS, France) mercredi 13 juillet 2011 20:30:25
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8
    Please : Search for questions similar to your own before submitting them to the community
    To be the AW6 successor, iWork MUST integrate a TRUE DB, not a list organizer !

  • Filter a column and a row based on two labels

    Hi
    Having a slight problem with an excel table and how to either filter or lookup the value I require.
    Basically the table is a skill matrix that I am trying to create into an app. The columns of the table are Name, and then all the separate areas (Area 1, Area 2, Area 3 etc). The rows are then the persons name in the name column and then a grading of that
    persons skills for each area. So the table looks look this:
    Name.       Area 1.        Area 2.      Area 3.
    John.            1.                1.             3
    Paul.             2.                1.             1
    I have created a gallery with all the names, and another gallery with all the areas - and I would like the values for the areas to show based on these 2 criteria. Tried Lookup which kept throwing up errors and also filter which again threw up errors. Is
    there any way to combine these to get the values showing in a label?
    Thanks

    Thanks. I tried that method and it works but I have too many areas to make it functional within the app experience.
    A bit more information:
    I have a gallery which is linked to Table 1 - this consists of the name of each person and an image - the image is what controls the gallery, touch it and you go to screen 2 which is that person's individual 'page'.
    On this page is the persons image, a label with their name, a drop down box and a text gallery. The drop down box and text gallery are linked to Table 2 - The dropdown is directed by a column in the table which is Zones and the text gallery is filtered by
    these zones into the areas within the zones:
    Zones            Areas            Name1            Name2             
    Name3 ....
    Zone 1           Area 1            3                     
    2                       3
    Zone 1           Area 2            1                     
    3                       2
    Zone 2           Area 3            3                     
    3                       3
    Zone 3           Area 4            1                     
    1                       3
    (This is an example of the table - the areas actually go into close to 100 and split into 6 zones).
    The Text gallery filter works upto a point - it gives me a Header which is based on the correct area - and only shows the Areas for the Zone picked from the drop down box. However, I would like the Body of the text gallery to give me the number for the name
    (which is the same name as picked from gallery 1).
    This is where I am having major problems (spent a week on this upto now and its nearly cost me 2 tablets when I think i have solved it and that little yellow triangle pops up in the body box).
    I have tried Lookup on Table2, using the name from gallery 1 as a the argument but it asks me each time to pick the right column to look in, which would work if I wanted the gallery only to work for a single Name but I would like it to show the rankings
    for the person who is picked from gallery1.

  • Payment Terms based on Value Date (UDF)

    Hi, is it possible and if how? I want to create a new Payment Term based on a value date which is maybe months ahead. So the docduedate is after this value date but the document shall already go into accounting.
    how is this easily possible?

    Hello,
    If you mean that the payment due date in the payment terms should be calculated on the basis of some date specified in a udf, it is not possible.
    But what you can do is use formatted search to calculate the due date based on the udf. apply this formatted search in due date field.
    Rahul

  • Set default values for StartMonth and EndMonth Parameter based on value selected from the previous parameter(Not cascading)

    I have a scenario where it has multiple parameters like.....
    Period which consists of "Year,Quarter,Month" as a values.
    When user selects "Year" value in "Period" Parameter then "FromMonth" has to set its default value as 36th month from now.
    Example: If user selects "Year" then "FromMonth" has to show "April-11".
    When user selects "Year" value in "Period" Parameter then "EndMonth" has to set its default value as current month.
    Example: If user selects "Year" then "FromMonth" has to show "March-14".
    If user selects "Month" Value in "Period" Parameter then it has to allow user to select the Month Range and again if user selects "Year" value in "Period" Parameter then StartMonth has to show 36th month from now and
    End Month has to show current month.
    Please help me how to resolve this issue.
    Thanks in Advance.

    Hi  Vasu_479,
    First, you need to create a dataset to set the StartDate and EndDate parameter's value using the query provided by Visakh. And then use the StartDate and EndDate parameter to filter the data in MDX query. Here is a sample query for your reference.
    select
    {[Measures].[Internet Sales Amount]
    } on columns,
    {[Date].[Date].members} on rows
    from(
    select
    STRTOMEMBER("[Date].[Date].&["+@StartDate+"]"):STRTOMEMBER("[Date].[Date].&["+@EndDate+"]")
    ) on columns
    from [Adventure Works]
    Hope this helps.
    Regards,
    Charlie Liao
    TechNet Community Support

  • How to select rows based on values from other table?

    I need to select all rows from TABLE1 whose time column is NOT between fromTime and toTime from TABLE2.
    For example, those table contain following rows:
    TABLE1
    |id |time |...
    |1 | 10 |...
    |2 | 20 |...
    |... | ... |...
    TABLE2
    |fromTime|toTime|
    | 3 | 6 |
    | 10 | 16 |
    | 20 | 25 |
    So, in the case above the first and second rows shouldn't be returned by the query since 10<=10<=16 AND 20<=20<25.

    Try
    -- code #1
    SELECT id, time
    from TABLE1 as T1
    where not exists (SELECT * from TABLE2 as T2
    where T1.time between T2.fromTime and T2.toTime);
    José Diz     Belo Horizonte, MG - Brasil

  • 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

  • Using Cursor and FOR LOOP to INSERT the data into table

    Hi all,
    I have SELECT statement that returns 3 rows:
    PROCESSNAME
    PROTDATE
    IMM
    2013-12-18
    Metrology
    2013-11-18
    CT
    2013-12-04
    SELECT  processName, MAX(NVL(protStartDate, protCreateDate)) AS protDate
        FROM TABLE(SEM_MATCH("{
                ?ipc rdf:type s:Protocol .
                ?ipc s:protocolNumber ?protNum .
                ?ipc s:protocolCreateDate ?protCreateDate .
                OPTIONAL {?ipc s:protocolSchedStartDate ?protStartDate }
                ?ipra rdf:type s:ProcessAggregate .
                ?ipra s:hasProtocol ?iprot .
                ?iprot s:protocolNumber ?protNum .
                ?ipra s:processAggregateProcess ?processName.
        }",sem_models("PROTS", "LINEARS"),NULL, SEM_ALIASES(SEM_ALIAS("","http://VISION/Data/SEMANTIC#"),SEM_ALIAS("s","http://VISION/DataSource/SEMANTIC#")),NULL))
            Group by processName
    Now I need to INSERT these values into the table along with the other values.
    these other values come from different table.
           INSERT INTO MODEL_CLASS_COUNTS (MODEL_NAME, CLASS_NAME, INS_COUNT, COUNT_DATETIME, PROCESS_NAME, PROT_DATE)
           VALUES
           ("$MODEL",     
                "${i}",
            (SELECT COUNT (DISTINCT S)  FROM TABLE(SEM_MATCH(
                            "{?s rdf:type :${i} . }",SEM_Models("$MODEL"),NULL, SEM_ALIASES(SEM_ALIAS("","http://VISION/DataSource/SEMANTIC#")),NULL))),
             SYSTIMESTAMP, %%here need to insert PROCESSNAME, PROTDATE%%
    t was giving me error:
    PL/SQL: ORA-22905: cannot access rows from a non-nested table item
    so i enclosed sparql query into single quotes.
    The code is as follows:
    declare
    type c_type is REF CURSOR;
    cur c_type;
    v_process varchar2(200);
    v_pdate varchar2(200);
    begin
    open cur for
           ' SELECT processName,  MAX(NVL(protStartDate, protCreateDate)) AS protDate   <-- it's complaining about this being too long identifier, i think...
            FROM TABLE
              (SEM_MATCH (
                            ?ipc rdf:type s:Protocol .
                            ?ipc s:protocolNumber ?protNum .
                            ?ipc s:protocolCreateDate ?protCreateDate .
                            OPTIONAL {?ipc s:protocolSchedStartDate ?protStartDate }
                            ?ipra rdf:type s:ProcessAggregate .
                            ?ipra s:hasProtocol ?iprot .
                            ?iprot s:protocolNumber ?protNum .
                            ?ipra s:processAggregateProcess ?processName.
                        }",SEM_Models("XCOMPASS", "XPROCESS"),NULL,    
              SEM_ALIASES(SEM_ALIAS("","http://VISION/Data/SEMANTIC#"),
              SEM_ALIAS("s", "http://VISION/DataSource/SEMANTIC#")),NULL))
               Group by processName';  
    loop
    fetch cur into v_process, v_pdate;
    exit when cur%NOTFOUND;
    --here I need to insert v_process , v_pdate into my table along with other values...
    dbms_output.put_line('values for process and prod_date are: ' || v_process || v_pdate );
    end loop;
    close cur;
    end;
    exit;
    Now, I get an error:
    ORA-00972: identifier is too long
    Does anyone know way around this?

    Hi,
      I tested something similar with insert into select  and it worked fine :
    insert into t_countries(ID,CITY ,POPULATION, DESCRIPTION, located, insdate )
    SELECT 1 id, city, o , city||' is a nice city' description,  max(nvl(locatedAt,'unknown')) as located,
      SYSTIMESTAMP
      FROM TABLE(SEM_MATCH(
        '{GRAPH :gCH {<http://www.semwebtech.org/mondial/10/countries/CH/> :hasCity ?cityID .
           ?cityID :name ?city .
           OPTIONAL{?cityID :locatedAt ?locatedAt .}
           ?cityID :population ?o .
        SEM_Models('VIRT_MODEL_MONDIAL'),
        SEM_Rulebases(null),
        SEM_ALIASES(SEM_ALIAS('','http://www.semwebtech.org/mondial/10/meta#'),
        SEM_ALIAS('prv','http://www.semwebtech.org/mondial/10/countries/CH/provinces/')
        null))
        group by city,o
        order by city;
    Or with execute immediate :
    declare
      v_country varchar2(200) :='http://www.semwebtech.org/mondial/10/countries/F/';
      v_text varchar2(2000);
    begin
    v_text := 'insert into t_countries(ID,CITY ,POPULATION, DESCRIPTION, located, insdate )
    SELECT 1 id, city, o , city||'' is a nice city'' description,  max(nvl(locatedAt,''unknown'')) as located,
      SYSTIMESTAMP
      FROM TABLE(SEM_MATCH(
        ''{<'||v_country||'> :hasCity ?cityID .
           ?cityID :name ?city .
           OPTIONAL{?cityID :locatedAt ?locatedAt .}
           ?cityID :population ?o .
        SEM_Models(''VIRT_MODEL_MONDIAL''),
        SEM_Rulebases(null),
        SEM_ALIASES(SEM_ALIAS('''',''http://www.semwebtech.org/mondial/10/meta#'') ),
        null))
        group by city,o
        order by city';
        dbms_output.put_line(v_text);
        delete from t_countries;
        execute immediate v_text ;
        commit;
    end;
    Marc

  • 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

  • Make 1 row turn into X rows, based on value X in column?

    Hello everyone, got a question for you! I've got a table as follows:
    ITEM_NUM,IN_STOCK
    1001A,2
    1001B,1
    1001C,2
    1001D,3
    I'd like to get the following output:
    1 1001A
    2 1001A
    3 1001B
    4 1001C
    5 1001C
    6 1001D
    7 1001D
    8 1001D
    So each row gets repeated for as many times as it has for the in_stock value. And down the left side, we get rownum.
    I can do this with PL/SQL code (a cursor to get both columns, and for each row, run a loop to place these into a collection). But if there's a way just to skip the loop and write a query, I'd rather do this!
    Thanks!
    -Thomas H

    Well you can pretty much use any row source here but I favour pipelined function for overall simplicity / clarity and performance.
    Personal Oracle Database 10g Release 10.1.0.2.0 - Production
    With the Partitioning, OLAP and Data Mining options
    SQL> CREATE TABLE t (item_num VARCHAR2 (5), in_stock NUMBER);
    Table created.
    SQL> INSERT INTO t VALUES ('1001A',2);
    1 row created.
    SQL> INSERT INTO t VALUES ('1001B',1);
    1 row created.
    SQL> INSERT INTO t VALUES ('1001C',2);
    1 row created.
    SQL> INSERT INTO t VALUES ('1001D',3);
    1 row created.
    SQL> CREATE OR REPLACE FUNCTION many (
      2    p_rows IN NUMBER)
      3    RETURN number_table PIPELINED
      4  IS
      5  BEGIN
      6    FOR l_row IN 1..p_rows LOOP
      7      PIPE ROW (l_row);
      8    END LOOP;
      9    RETURN;
    10  END;
    11  /
    Function created.
    SQL> SELECT ROWNUM, item_num
      2  FROM   t, TABLE (many (in_stock));
        ROWNUM ITEM_
             1 1001A
             2 1001A
             3 1001B
             4 1001C
             5 1001C
             6 1001D
             7 1001D
             8 1001D
    8 rows selected.
    SQL>

  • Credit check at goods issue and release authorziation based on value

    Hi,
    I am doing credit management config. My reqmt. is to have credit check at goods issue only. Done this through credit group in automatic credit management config. I have used static check with both open orders and open deliveries checked.
    open sales order (delivery not created) value is not updating in the credit exposure field in FD32 can u tell me what can be the problem (I have maintained the subtotal value A in pricing procedure)
    My 2nd requirement is based on the range of credit value, documents should be released. i.e., Credit limit is 1Lakh. Now when it exceeds by 50000, credit manager is authorized to release in VKM5. If it exceeds & between 50000 - 1Lakh, Finance Head should be authorized to release in VKM5 and finally it exceeds above 1Lakh , VP Finance should be authorized to release. How do we handle this, pls. give me solution for the above scenario
    Thanks
    Dhina

    HI
    > I am doing credit management config. My reqmt. is to have credit check at goods issue only. Done this through credit group in automatic credit management config. I have used static check with both open orders and open deliveries checked.
    > open sales order (delivery not created) value is not updating in the credit exposure field in FD32 can u tell me what can be the problem (I have maintained the subtotal value A in pricing procedure)
    Please Check the OSS Note 18613 that gives the check list for credit management setings
    > My 2nd requirement is based on the range of credit value, documents should be released. i.e., Credit limit is 1Lakh. Now when it exceeds by 50000, credit manager is authorized to release in VKM5. If it exceeds & between 50000 - 1Lakh, Finance Head should be authorized to release in VKM5 and finally it exceeds above 1Lakh , VP Finance should be authorized to release. How do we handle this, pls. give me solution for the above scenario
    Please discuss with your ABAP and Basis Consultant.
    Regards,
    Phani Prasad

  • 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

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

  • Counting rows based on consecutive dates

    I need some guidance. I have a database of drug fills from our data warehouse. There is a unique row for every drug filled. I a general rule, there is a 30 day prescription filled each month, and my research question needs me to look at consecutive months filled.
    So, if I have
    Name, Drug_Name, Fill_Date
    John Doe, DrugX, 05-2010
    John Doe, DrugX, 06-2010
    John Doe, DrugX, 07-2010
    John Doe, DrugX, 08-2010
    Mary Jane, DrugX, 05-2010
    Larry Smith, DrugX, 06-2010
    Larry Smith, DrugX, 07-2010
    John Doe, DrugX, 12-2010
    Larry Smith, DrugX, 09-2010
    Larry Smith, DrugX, 12-2010
    I need to identify patients with at least 3 consecutive months of a drug – so in the case above, that would only be John Doe. I can just do a unique count per patient and look at >= 3, because then I would also pick up Larry Smith who has 4 months of prescriptions, but not 3 consecutive months.
    Suggestions?
    Thank for the help.
    Rich
    Edited by: Ricco on Oct 19, 2010 11:19 AM

    Hi,
    Whenever you have a question, please post the sample data in a form that people can use to re-create the problem and test their ideas.
    For example:
    CREATE TABLE     table_x
    (      name          VARCHAR2 (20)
    ,      drug_name     VARCHAR2 (10)
    ,      fill_date     DATE
    INSERT INTO table_x (name, drug_name, fill_date) VALUES ('John Doe',    'DrugX', TO_DATE ('05-2010', 'MM-YYYY'));
    INSERT INTO table_x (name, drug_name, fill_date) VALUES ('John Doe',    'DrugX', TO_DATE ('06-2010', 'MM-YYYY'));
    INSERT INTO table_x (name, drug_name, fill_date) VALUES ('John Doe',    'DrugX', TO_DATE ('07-2010', 'MM-YYYY'));
    INSERT INTO table_x (name, drug_name, fill_date) VALUES ('John Doe',    'DrugX', TO_DATE ('08-2010', 'MM-YYYY'));
    INSERT INTO table_x (name, drug_name, fill_date) VALUES ('Mary Jane',   'DrugX', TO_DATE ('05-2010', 'MM-YYYY'));
    INSERT INTO table_x (name, drug_name, fill_date) VALUES ('Larry Smith', 'DrugX', TO_DATE ('06-2010', 'MM-YYYY'));
    INSERT INTO table_x (name, drug_name, fill_date) VALUES ('Larry Smith', 'DrugX', TO_DATE ('07-2010', 'MM-YYYY'));
    INSERT INTO table_x (name, drug_name, fill_date) VALUES ('John Doe',    'DrugX', TO_DATE ('12-2010', 'MM-YYYY'));
    INSERT INTO table_x (name, drug_name, fill_date) VALUES ('Larry Smith', 'DrugX', TO_DATE ('09-2010', 'MM-YYYY'));
    INSERT INTO table_x (name, drug_name, fill_date) VALUES ('Larry Smith', 'DrugX', TO_DATE ('12-2010', 'MM-YYYY'));
    COMMIT;Also, post the exact output you want. In this case, it's probably very simple. It's unclear from your description, but I think you want this:
    NAME                 DRUG_NAME                                                 
    John Doe             DrugX                                                      Here's one way to get those results from that data:
    WITH  got_month_num      AS
         SELECT DISTINCT  name
         ,           drug_name
         ,           MONTHS_BETWEEN ( TRUNC (SYSDATE,   'MONTH')
                              , TRUNC (fill_date, 'MONTH')
                             ) AS month_num
         FROM          table_x
    --     WHERE          ...     -- Any filtering goes here
    ,     got_group_num     AS
         SELECT     name
         ,     drug_name
         ,     ROW_NUMBER () OVER ( PARTITION BY  name
                                   ,                    drug_name
                             ORDER BY        month_num
                           ) - month_num     AS group_num
         FROM    got_month_num
    SELECT DISTINCT  name,     drug_name      
    FROM             got_group_num
    GROUP BY        name,     drug_name,  group_num
    HAVING           COUNT (*)       >= 3
    ORDER BY      name,     drug_name
    ;I'm guessing at some things.
    For example, you didn't say what role (if any) drug_name plays in this problem, and it's hard to guess since every row has the same drug_name.
    I'm guessing that every distinct combination of name and drug_name is a world of its own, having nothing to do with rows that have the same name but different drug_names, or the same drug_name but different names.
    This assumes that name uniquely identifies each patient.
    This does not assume that there is only one row per name and drug_name in each month, or that all fill_dates are at the same point in the month.
    The query above does require the fill_dates to be in consecutive calendar months. If one fill_date is January 31, 2010, and the next fill_date for the same patient and drug is March 1, 2010, then the rows are not considered to be consecutive, even though there are only 29 days between fill_dates.
    Depending on your data and your requirtements, the first sub-query (got_month_num) may not be necessary.
    A "group" (as defined by group_num) is a set of rows for the same patient and drug in consecutive months. If we number the months with consecutive integers in oreer by date, and number the rows with consecutive integers also in order by date, then the difference between those integers will be constant for all ros in the same group.
    Edited by: Frank Kulash on Oct 19, 2010 2:48 PM

Maybe you are looking for

  • How to configure a Logical System for XI External System

    I'm following the 'How to configure SAP XI to use the standard SAP communications APIs (idoc, pabi, rfc) from external system - How to create XI content with the Integration Builder' document. I have everything configured, but in section 6.7 when I t

  • E-Commerce 5.0 for ERP and re-using a Quote

    We have an E-Commerce 5.0 for ERP environment that has been up and running for three years now. Everything is working great and we've made many custom enhancements through the years, but there is one that business is asking for that I've not been abl

  • Using Native SQL in Web Dynpro for ABAP

    Hi folks, I am trying to access an oracle database in web dynpro for ABAP via Native SQL. I am able to read row by row from the database into a work area, but I am unable to read the whole table from the database into an internal table. Please advise

  • Error when managing archive mailboxes through ECP

    Hi I deploying Exchange 2013 CU2 (fully patched) next to our old 2007. I have 3 Mailbox-server 2 CAS-servers and 1 Archive-server Everything is working ok until I started giving migrated users an archive mailbox. It Archive mailbox works OK for the u

  • Finding Restrictions passcodes in IOS 5

    My daughter has been playing with her itouch settings and has put on passcode restrictions, however she no longer has any idea what they are!  I have tried using a back-up extractor software however it does not give this information in IOS 5 and I ca