CREATING A TRIGGER THAT PICKS UP THE LAST INSERTED RECORD

Hello everybody
my question. is it possible to embed a sql query whitin a trigger? the thing is that when I have to insert the value, this actually would have to be retrieved from another table. It is an AFTER INSERT, but it needs to know which name I inserted in table 1 in order to also insert it into table 2.
More specifically. Imagine a table with usernames and passwords that I populate as I set them up
Then I need a trigger that as it sees that I have entered that username it takes it and populates another table with that plus a generated sequence that could be the result of some string function
CREATE OR REPLACE
TRIGGER GENERATE_SEQUENCE
AFTER INSERT ON USERS_TABLE
FOR EACH ROW
BEGIN
insert into GENERATED_SEQUENCES_TABLE (lastinserted_name,surrogate_key)
values(SELECT USERNAME FROM USERS_TABLE WHERE USERID....., SUBSTR (lastinsertedname¦¦ password), 1,12);
END;
so, this lastinserted name is what I am trying to retrieve. I mean if it is not madness to insert a sql query in the way I have done it, I could write in the query to select the highest ID from the PK and that would give me the last inserted name.
thanks a lot
Alvaro

In an insert trigger you can reference all the inserting values with :new.column_name, hence there's no need to select from the USERS_TABLE table:
CREATE OR REPLACE
TRIGGER GENERATE_SEQUENCE
AFTER INSERT ON USERS_TABLE
FOR EACH ROW
BEGIN
insert into GENERATED_SEQUENCES_TABLE (lastinserted_name,surrogate_key)
values(:new.USERNAME, ...);
END;
/Max
[My Italian Oracle blog|http://oracleitalia.wordpress.com/2010/02/05/gestione-degli-errori-in-sql-con-log-errors/]

Similar Messages

  • Retrive a record before the last inserted record

    Hi,
    I use simple select statement to retrive records where cola = 'Yes':
    select * from tbl1
    where cola = 'Yes';
    The result gives me about 10 records with different date.
    From the above result, I want to get the record right before the last inserted record according to the date field; which means I can not use MAX function (all I want just one record).
    If I write a function to return a date and passes it back to the SELECT statement, I'll get a date for each record, which I don't want.
    I know there's a way to do that in PL/SQL.
    Plese help me.
    pem

    select * from (
    select * from
    (select * from (select * from (table> order by <date> desc) where rownum < 3)
    order by <date>) where rownum =1

  • How to get the last inserted record from a table ?

    :-) Hiee E'body
    I work on Oracle 8i and need to get the last
    record inserted in a table.
    I have tried using rownum and rowid pseudo-columns
    but that doesn't work.
    Can you please help me out ?
    :-) Have a nice time
    Vivek Kapoor.
    IT, Atul Ltd.,
    India.

    I'm not sure about 8i features.
    I assume here that you don't have 'Date-Time' stamp columns on the table which is the easiest way to determine the last inserted row in the table.
    If not try the following :-
    select address, piece, SQL_TEXT
    from V$SQLTEXT
    where upper(sql_text) like '%INSERT INTO TABLE_NAME%'
    Substiute the TABLE_NAME with the name of the actual table.
    Have fun.
    Regards,
    Shailender
    :-) Hiee E'body
    I work on Oracle 8i and need to get the last
    record inserted in a table.
    I have tried using rownum and rowid pseudo-columns
    but that doesn't work.
    Can you please help me out ?
    :-) Have a nice time
    Vivek Kapoor.
    IT, Atul Ltd.,
    India.

  • How to create a formula that shows only the last date of a series of dates

    I have a report that shows a series of dates that 'notes' were created on a particular file. I want the report to only show the date of the last note that was created instead of showing all the dates. Ive tried using 'Maximum ()' which does not work.
    Any suggestions?

    Either order the dates in ascending order and place the date field in the group footer
    -or-
    order the dates on descending order and plade the date field in the group header.
    HTH,
    Jason

  • Fetching the last inserted record

    How can I fetch the last record inserted into oracle table?

    Hi Waleed / Bhavesh
    In pure RDBMS terms there is no concept of a first / last record. Also the query that Bhavesh has give makes an assumption that emp_n have been sequentially or inserted in some form of continuous incremental format.
    It is not adviseable to use ROWNUM and ORDER BY together since Oracle allocates ROWNUMs before it actually orders the data

  • How can I get the last / newest record of a table?

    Hi,
    I am developing an ecard app that has a create greeting page, a preview page with edit and send buttons and an edit page.
    I got he insert working, and on the preview page I created a master record page (displays all records), and delete all unecessary designs. Doing it this way also gives me the 'edit' button, so people are able to edit their page.
    How do I get only the last record displayed though? At the moment it loops through all records and displays them in sets of 10. I found the variable that holds the totla count of records ('$totalRows_rs7417_content1'), but how do I (re-)write the script so it ONLY diplays the last record?
    I need to get the ID of this record as I am writing this into the PARAMs of the object and embed tags of my message .swf (this picks up the ID and based on that sucks the greetings text out of the database via another php script.
    Also, from this page, how can I send an email to the sender (ie creator of the message) as well as the recipient? Both email addresses are in the databse so should be part of the erecord returned.
    Thanks,
    Nik

    -----
    OK, So how do I recreate what I got in a non-ADDT list?
    well, when you´re just about to display one certain record, the term "list" is somewhat inappropriate anyway.
    What you´d simply need to do IMHO, is using DW´s native functions to create the basic "SELECT * FROM table_name ORDEr BY ID DESC" query, add "LIMIT 1" manually, and display the desired "dynamic text" placeholders in 1 table cell -- don´t think there were any need for all the fancy stuff
    (sorting, filtering etc) provided by ADDT´s list, as it´s just 1 record.
    It also occurred to me just now that finding the last record that has been added *may-* notbe enough if the site gets used a lot by our executives (I am thinking of a situation where 2 or three peolpe create greetings at the same time and press submit and then getting each others messges rather than their own).
    in this case you might want to additionally store the respective executive´s "kt_login_id" session variable -- because it´s this unique "identifier" which should be used to show the last inserted record of the person who actually inserted it, means adding a "WHERE submitter_id" equals the session variable kt_login_id - clause to the query.
    When creating a non-ADDT list that´s at some point based on detecting a user session, you´ll BTW need to insert at line 1
    I can't seemt o insert it on the page as it is looking for a insert, update or delete bahaviour on the page which of course I don't have
    please search these forums for several posts I made which explain my "use dummy table" approach that´s made for cases when you actually don´t have anything to insert/update/delete, but need "something" for ADDT´s send email behaviours.
    Cheers,
    Günter Schenk
    Adobe Community Expert, Dreamweaver

  • Getting the last inserted ID

    I found out about a mySQL function that will get the last inserted autoincrement ID and I want to use it in my page. The prepared statement i am using look like this.
    PreparedStatement insertQuestion1 = ConninsertQuestion1.prepareStatement("INSERT INTO Question.question (Topic_ID, Description, Image, Author, Created_Date, Max_Score, Question_Type)  VALUES ('" + questionData.topicID + "', '" + questionData.questionText + "', '" + questionData.questionImage + "', '" +insertQuestion1__username+ "', '" + currentDate + "', " + questionData.maxScore + ", '" + questionData.questionType + "') ");
              insertQuestion1.executeUpdate();there is a function in mysql which looks like this.
    int mysql_insert_id (resource [link_identifier])
    How can i implement this in my code so i will be able to use the integer value later on to insert more records in another table.
    Help would be much appreciated
    Thanks

    If you are using Java1.4 the approach would be to use :
    public boolean execute(String sql,
    int autoGeneratedKeys)
    throws SQLException
    where the autoGeneratedKeys flag is set to Statement.RETURN_GENERATED_KEYS
    After the insert you can call the method :
    public ResultSet getGeneratedKeys()
    throws SQLException
    Which will return a ResultSet containing the mySQL auto-generated keys.
    Check the documentation
    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html
    Note that PreparedStatement inherits these methods from Statement

  • Getting the last insert id

    Hi there,
    I'm trying to get the id of the last inserted record. Normally would use $last_id = mysql_insert_id() after the insert statemant but I can't work out how to get this value when I use a ADDT insert transaction.
    Any help much appreciated.
    Cheers

    I´m locking this thread because the OP has additionally added a related question to an existing thread, and a solution to this problem has been provided there too: using  mysql_insert_id() with the ADDT

  • Last inserted record

    HI,
    we have created a table with a field ID.
    we have inserted 1000 records in that table,.
    I want to retrieve only the last inserted record.
    How it's possible?
    is it possible with rowid?
    e.g:
    CREATE TABLE TEST(id number(2));
    insert into TEST values(1);
    insert into TEST values(2);
    insert into TEST values(3);
    insert into TEST values(4);
    insert into TEST values(5);
    In this case i want to retrieve only 5.
    How we can achieve this?

    There is no concept of order in a heap table. Blocks can be reused so the ROWID cannot ever be used to determine when a row was inserted. The only way to determine the last row that was inserted into a table is to use a timestamp and/or a sequence column. If you need to determine the last inserted row and you don't already have a timestamp or sequence column, you need to add one.
    HTH
    David

  • Retrive last inserted  record  from database table

    Hi,
    some body inserting a record into table 'A' through some procedure/java program.i want to retrive the last inserted record from database table.records are not stored in order.Can any body help me.

    In general, unless you are storing a timestamp as part of the row or you have some sort of auditing in place, Oracle has no idea what the "first" or "last" record in a table is. Nor does it track when a row was inserted.
    - If you have the archived logs from the point in time when the row was inserted, you could use LogMiner to find the timestamp
    - If the insert happened recently (i.e. within hours), you may be able to use flashback query to get the value
    - If you're on 10g or later and the table was built with ROWDEPENDENCIES and the insert happened in the last few days and you can deal with a granularity of a few seconds and you don't need 100% accuracy, you could get the ORA_ROWSCN of the row and convert that to a timestamp.
    If this is something you contemplate needing, you need to store the data in the row or set up some sort of auditing.
    Justin

  • GET LAST INSERTED RECORD

    I am fairly new to flex. So please bear with me no this
    question.
    I would like to get MYSQL ID of the last record I inserted.
    MSQL has as function LAST_INSERT_ID() that is connection based and
    will return the last id of the last inserted record. My thought was
    in the function contained within the cfc to do 2 queries insert the
    record and return the last id directly after (see below). However,
    I don't know how I would read the results back into flex. I am
    unsure how to write the event handler. Thanks
    <cffunction name="insertUser" access="remote"
    returntype="query" >
    <cfargument name="SSN" required="false" type="string"
    hint="SSN"/>
    <cfargument name="FNAME" required="false" type="string"
    hint="FNAME"/>
    <cfargument name="LNAME" required="false" type="string"
    hint="LNAME"/>
    <cfargument name="CLIENTID" required="false"
    type="string" hint="NEW CLIENTID"/>
    <cfquery name="insUser" datasource="DBT">
    INSERT INTO CLIENT (SSN, FNAME, LNAME) VALUES (
    <cfqueryparam value="#ARGUMENTS.SSN#"
    cfsqltype="CF_SQL_VARCHAR" maxlength="12"/>,
    <cfqueryparam value="#ARGUMENTS.FNAME#"
    cfsqltype="CF_SQL_VARCHAR" maxlength="20"/>,
    <cfqueryparam value="#ARGUMENTS.LNAME#"
    cfsqltype="CF_SQL_VARCHAR" maxlength="30"/>)
    </cfquery>
    <cfquery name="qRead" datasource="DBT">
    SELECT last_insert_id() AS CLIENTID
    </cfquery>
    <cfreturn qRead >
    </cffunction>

    I assume you have LCDS installed with CF and you are using
    the remote object service,
    <mx:RemoteObject
    id="myService"
    destination="ColdFusion"
    source="full.path.to.cfc"
    showBusyCursor="true">
    <mx:method name="insertUser"
    result="insertUser_result(event)" />
    </mx:RemoteObject>
    <mx:Scrpit>
    private function insertUser_result(event:ResultEvent) {
    trace(event.result);
    event.result will be the id of the newly inserted record.
    BTW, I would highly recommend you looking into the data
    management servcie. the SQLAssembler can spare you of the CF code
    for simple CRUDs like this.

  • How to pick up the last value of the input string

    Hi there,
    I have a requirement in which I have to pick up the last value of the input string.
    I don't know the field length, it could be 10 line, it could be 4 line and it could be even 1 line.
    Another problem is that the field contains all the alphanumeric values so the sort function is not working.
    I believe I need to write a UDF but not sure exact what and how.
    Can some body please help me solving this issue.
    Input.
    1.Abc
    2.abc123atxx.com
    3.(980)771-2341
    4.
    5.518VR50V58AD10DSAYBDSAFDSIEGHA:1
    In that case I only need to pickup the last value i.e. 518VR50V58AD10DSAYBDSAFDSIEGHA:1
    Output
    518VR50V58AD10DSAYBDSAFDSIEGHA:1
    Note:
    1. Length is unknown
    2. Alphanumeric data
    Thanks,

    Hi karthick Lakkar,
    Thanks for your quick response but unfortunately I am getting mapping exception.
    What I did is create a UDF with 2 input
    INPUT
    a string
    b string
    and then this code
    int Length=Integer.parseInt(a);
    int requiredLength=Integer.parseInt(b);
    if(Length<=requiredLength)
    return(a);
    else
    return a.substring((Length-requiredLength),Length);
    I am wondering about the input as well.
    At present I am doing
    KTEXT + KTEXT --- UDF
    + does represent concat, means same input will go to the UDF
    This is the error which I am getting
    Exception:[java.lang.NumberFormatException: For input string: "Kevin Farrar"] in class com.sap.xi.tf._MM_XXXXXXXXXXXXXX_ method calculate[Kevin Farrar, Kevin Farrar, com.sap.aii.mappingtool.tf7.rt.Context@6dbf19db]

  • Is it possible to create a variable in bex with the last work day?

    Hi Gurus
    Is it possible to create a variable in bex with the last work day?
    Actually end-user every day open queries,
        - Put in selection date day - 1 or
        - put last Friday if the day is Monday or
        - put last Thursday if the day is Monday and Friday is holiday (in a calendar for example 25 the December).
    Please do the needful. It is urgent
    Thanks in advance
    Raj

    Try this logic in a customer exit:
    DATA:  l_s_range TYPE rsr_s_rangesid.
    DATA:  X_PERIOD LIKE T009B-POPER,
               X_YEAR   LIKE T009B-BDATJ.
      CASE I_VNAM.
      WHEN 'ZPREVWORKDAY'.
        DATA: l_DayOfWeek(1) TYPE C,
              l_act_date     TYPE d,
              l_prev_date    TYPE d.
        l_act_date = sy-datum.
        CALL FUNCTION  'DATE_COMPUTE_DAY'
             EXPORTING DATE = l_act_date
             IMPORTING DAY  = l_DayOfWeek.
        CASE l_DayOfWeek.
          WHEN '1'.
            l_prev_date = l_act_date - 3.
          WHEN '2'.
            l_prev_date = l_act_date - 1.
          WHEN '3'.
            l_prev_date = l_act_date - 1.
          WHEN '4'.
            l_prev_date = l_act_date - 1.
          WHEN '5'.
            l_prev_date = l_act_date - 1.
          WHEN '6'.
            l_prev_date = l_act_date - 1.
          WHEN '7'.
            l_prev_date = l_act_date - 2.
        ENDCASE.
        l_s_range-low  = l_prev_date.
        APPEND l_s_range TO e_t_range.
    ENDCASE.
    Edited by: Tyler Blouse on Feb 13, 2008 8:28 PM

  • Having stopped audio with a swf inside a sidelet can someone create a swf that will resume the audio

    Ok, rick is going to post the fla of this file and I will
    post the swf. Basically this is all about having a slide that has
    audio running all the way through and enabling the user to roll
    over a sidelet and have the video and audio stop playback.
    At present, the max you can achieve is, to stop video. The
    audio keeps going and of course everything gets out of
    sync. Rick has create a swf that you input into a sidelet (
    after having imported your image or video ) which stops the audio.
    Fantasitc. Unfortunatly he was not successful in creating a swf
    that will resume the audio.
    So there is the mission. To create something that will resume
    the audio, be it a swf inside the sidelet or something else.

    Hi there paul. Am I right in thinking that your code will
    mute the audio. In my situation this would cause problems becasue
    you would roll over the sidelet - the audio would go silent and
    when you rolled off, or resumed the audio, it would have been
    playing so again the video and audio will be out of sync.
    Rick - rather than another swf which would activate the audio
    and video when you roll off the sidelet ( while that is the perfect
    solution ) what about looking at a button the user can press to
    resume things, maybe Im wrong but that sounds a little easier.
    ( however for all those reading this that is not really the
    solution I am looking for, what Im looking for is the above
    solution where you can just roll off and on and so on )

  • How to create a user that can login the LDAP?

    I want to create a user that can login the OID/LDAP. I know how to create a user, it is allowed to login OIDDAS, but I also want the user to grant access to ldap directly. How do i do that?
    And how can I give it read rights and or update/delete rights on a specific tree?
    Regards
    Eelco

    Eelco,
    did you see the OiD developers guide? Here you find some examples how to create users in OiD using pl/sql or java.
    http://download-west.oracle.com/docs/cd/A97329_03/manage.902/a95193/smplcode.htm#637294
    how to use directory access control can be found in
    http://download-west.oracle.com/docs/cd/A97329_03/manage.902/a95192/access.htm#1054232
    --Olaf

Maybe you are looking for