Trigger that checks if value exists in another table before insert

Hi,
Can any one help me with the correct code.
I am trying to write a trigger that checks if the new value (:new.T1) does not exist in another table (T2) before entering it (in T1).
Create or replace trigger T1
BEFORE
insert on T1
for each row
Declare
x Number;
begin
SELECT Count (*) INTO x
From T2 WHERE T2.Col1 = :new.T1;
IF (x > 1 or x = 1) Then
DBMS_OUTPUT.PUT_LINE('This value has been used before try another one.');
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO T2 (Col1) values (:new.T1);
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('This value has been used before try another one.');
end;

I think this question is suitable for the SQL and PL/SQL forum.

Similar Messages

  • Delete allowed in a multirow blk only if no records exist in another table

    How can I delete an existing row in a multirow block after checking that no records exist in another table ?
    How do I proceed please ?
    I know I need to check the primary keys of both tables to do that . Please help.

    I've written the following code in the KEY-DELREC trigger :
    DECLARE
    *     Fail EXCEPTION;*
    *     alert_title varchar2(100) := null;*
    *     p_button_choice number := 0; -- 10g : for Stop_Alert, Caution_Alert & Note_Alert*
    *     cnt NUMBER;*
    *     choice NUMBER;*
    Begin
    *     If :system.record_status NOT IN ('INSERT', 'NEW') THEN -- can be CHANGED or QUERY mode*
    *          begin*
    *          SELECT count(AMD_CODE)*
    *          INTO cnt*
    *          FROM t_mmamd,t_amdtype*
    *          WHERE AMD_CODE = :AMD_CODE*
    *          AND MMA_AMD_CODE = AMD_CODE;*
    *     IF cnt > 0 THEN*
    Alerts.Stop_Alert('Error: IMDG Code '||:AMD_CODE||'Delete not allowed!!Exists in t_mmamd table', choice);
    RAISE FORM_TRIGGER_FAILURE;                       
    *          ELSE*
    *          alert_title := 'Are you sure to remove this record ?';*
    *          Alerts.Stop_Alert_YesNo (alert_title, p_button_choice);*
    If p_button_choice = 1 Then
    *     delete_record;*
    End if;
    END IF;
    end;
    Else -- record status is in INSERT or NEW mode
    *          delete_record;*
    *     End if;*
    End;
    It works okay and prevents me from deleting records in the other table . However I get the following errors when I try to delete a record which doesn't exist in t_mmamd table :
    Could not resolve record(2 tries) keep trying?
    Error : 40501 - oracle Error unable to reserve record for update or delete .

  • SharePoint Designer Workflow to check if value exists in any item in SharePoint List

    Hi,
    I've two column in SharePoint List. I want to check using SharePoint Designer 2013, if value exists in any item in SharePoint List for these two columns "PR NO" and "Part No". Thanks
    Can you please help me in SharePoint Designer how to write condition / steps for this. Thanks.

    Why are you making things complicated for yourself by building a workflow via SharePoint designer 2013.
    I had a to do a similar task in the past and running powershells was an easier and faster approach.
    Take a look at this Microsoft technetarticle I wrote a while back.
    http://social.technet.microsoft.com/wiki/contents/articles/25125.sharepoint-2013-powershell-to-copy-or-update-list-items-across-sharepoint-sites-and-farms.aspx
    Even though the above article talks about updating an existing list, you can focus on the condition where the powershell will loop through the list to see if any change has been made. You can add a condition to this change.
    Daniel Christian (MCTS)

  • How to check node value exists or not?

    for example
    <Hi>1</Hi>
    here for Hi value exists or not need to check.

    SQL> create table MY_XML_TABLE of XMLTYPE
      2  /
    Table created.
    SQL> insert into MY_XML_TABLE values ( XMLTYPE('<FOO><H1>FOO</H1><H2/></FOO>') )
      2  /
    1 row created.
    SQL> commit
      2  /
    Commit complete.
    SQL> set feedback on
    SQL> select *
      2    from MY_XML_TABLE
      3   where XMLExists('$x/FOO/H1' passing OBJECT_VALUE as "x")
      4  /
    SYS_NC_ROWINFO$
    <FOO>
      <H1>FOO</H1>
      <H2/>
    </FOO>
    1 row selected.
    SQL> select *
      2    from MY_XML_TABLE
      3   where XMLExists('$x/FOO/H1/text()' passing OBJECT_VALUE as "x")
      4  /
    SYS_NC_ROWINFO$
    <FOO>
      <H1>FOO</H1>
      <H2/>
    </FOO>
    1 row selected.
    SQL> select *
      2    from MY_XML_TABLE
      3   where XMLExists('$x/FOO/H2' passing OBJECT_VALUE as "x")
      4  /
    SYS_NC_ROWINFO$
    <FOO>
      <H1>FOO</H1>
      <H2/>
    </FOO>
    1 row selected.
    SQL> select *
      2    from MY_XML_TABLE
      3   where XMLExists('$x/FOO/H2/text()' passing OBJECT_VALUE as "x")
      4  /
    no rows selected
    SQL>

  • How to Check a Value from a Lookup table??

    Hi Experts,
    I have 2 lookup tables.
    If a Value in Lk1 is selected, i need to check if that selected value is present in Lk2 table.
    Ex:
    MF table (Look up 1)
    0001
    0002
    0003
    0004
    Ecc Table (Look up 2).
    0001
    0003
    0004
    0005
    Note: User will not have access to Look up table 2.
    So, When user selects any value in MF table (Look up 1) then the validation should check if that value is present in Look uptable 2 (Ecc table).
    If present then true Else False.
    Did someboday face a similar situation!!!
    Can anyone help??
    Kind Reagrds
    Eva

    Hi Eva,
    I see your requirement this way...
    1) I will add two fields to your current Lookup table and link to one field in the main table, say the field name is LK
    2) Create a Lookup Flat Multi Valued field in the main table which will be linked to a lookup table name systems which has different remote system names used in the landscape.By this field i will be identifying whether the record is for remote system MF or Remote System ECC or both
    Say the your current Lookup table structure is
    Code
    Name
    What i do is add two fields to the current structure
    Code
    Name
    ECC
    MF
    And the sample data will be like this
    Code    Name           ECC       MF
    0001      xx              Yes      Yes
    0002      xx              No        Yes
    0003      xx              Yes      Yes
    0004      xx              Yes      Yes
    0005      xx              Yes       No
    By this way i can easily validate the record which is selected in the main table exists in ECC and MF Systems based on the systems field in the main table.
    Validaiton Code for checking the record exists in ECC
    If( HAS_ANY_VALUES(systems,ECC)=TRUE,LK1.ECC=Yes)
    Validaiton Code for checking the record exists in MF
    If( HAS_ANY_VALUES(systems,MF)=TRUE,LK1.MF=Yes)
    Regards
    Sowseel

  • How to check all columns existing in a table?

    Hello.
    I'm writing a function that returns average value of every numeric column existing in a database.
    I have a general idea how to do it, but I need just one more thing, look at the expamle:
    select table_name from user_tables where rownum=1
    this allows me to select names of all tables, and then I can access them 1 by 1...
    But now i have a little problem - how to access all the atributes in selected table in this way?
    Oh, and I have a problem with this rownum... For example it works for 1 (shows 1st row - name of first table) but does not for 2, or greater number :(.
    And expresions like rownum < 5 work, but rownum > 3 not :/. What may be the reason?
    Thank you for help!
    Regards.

    user13483761 wrote:
    Thanks a lot! This 3 atributes is all I need, its a way lot easier than I thought before. I simply use cursor loop and your advices.
    Almost got working code - but there is 1 error telling that select is incorrect :/. Why is that?
    create or replace
    FUNCTION SHOW_ALL
    RETURN VARCHAR2 IS
    v_ret VARCHAR(100):='Null';
    BEGIN
    DECLARE
    CURSOR cur_stats IS SELECT table_name, column_name, data_type
    FROM user_tab_columns;
    v_zdanie VARCHAR(100);
    BEGIN
    FOR v_cur IN cur_stats LOOP
    IF v_cur.data_type = 'NUMBER'
    THEN
    strike
    --> select 'In table ' || v_cur.table_name || ' average value of ' ||--
    --> v_cur.column_name || ' is:' || avg(v_cur.column_name)--
    --> into v_zdanie--
    --> from v_cur.table_name;--
    strike
    >
    dbms_output.put_line(v_zdanie);
    END IF;
    END LOOP;
    RETURN v_ret;
    END;
    END SHOW_ALL;
    select 'In table ' || v_cur.table_name || ' average value of ' ||
    v_cur.column_name || ' is:' || avg(v_cur.column_name)
    into v_zdanie
    from v_cur.table_name;
    sql_developer tells that this 'table or perspective does not exist' or sth like that, I translated from my native language.You are missing lot of things in the function, you are hard coding the return value to null?
    What you should do is as below:
    remove the part what you have written, i have strike that above. declare a variable your_select_statement VARCHAR2(1000);
    your_select_statement := 'select nvl(avg('||v_cur.column_name||'),0) from '||v_cur.table_name;
    execute immediate your_select_statement into v_zdanie;
    dbms_output.put_line('In table ' || v_cur.table_name || ' average value of ' ||v_cur.column_name || ' is:' ||v_zdanie);

  • How do you sort a table that contains links to cells in another table?

    This is something that I used to be able to do in Numbers but since 2 or 3 updates ago this doesn't seem to happen.
    The problem I have is that I have a table that includes cells that are a sum of a number of cells from another table. When I try and sort by a column all the info in the cells change because, I imagine, the commands linking to the cells in the other table are offsetting by however many rows a particular row has moved.
    This didn't used to happen; it used to hold on to the same data and links regardless of where the sort function moved a row to.
    Had a look through the help pages but can't find anything about it. Has anyone found a way around this?
    Thanks in advance.
    Matt

    Hi mmatt,
    There are several ways to create sort-safe formulas. Without knowing what you are doing in your table it is hard to give specific advice but in general INDEX(), OFFSET() and I think INDIRECT() are sort safe- ie they will ocntinue to point to the same cell wherever they are in your sort.
    If you want specific advice you would need to provide more info.
    quinn

  • Condition that checks the value of an Item derived from a select list

    I want to conditionally display and hide items in a region based on a select list item.
    Some items will display when the select list is at the default (%null%) and others will be displayed when the select list user selects from the select list.
    The display is then updated when the "SAVE" button is pressed and the page processed.
    How do I test the select list item to be null. The condition looks like this;
    Type: PL/SQL Expression
    :P1_SELECT is null
    I also tried, :P1_SELECT is not null and :P1_SELECT = '%nul%'.
    The latter changed the condition to :P1_SELECT = ''
    How can I test the valu in P1_SELECT?
    tia,
    Sam
    Message was edited by:
    After a long day I saw that I did not write the condition correctly. Mea culpa.
    slavanaway

    I had the problem wrong.
    The issue was a second field that could have a Y or N or null. When I checked it in PL/SQL expression as
    :P_YN != 'Y' and :P_SELECT is null
    assuming the null condition would resolve as != 'Y' I had to do an explicit check as
    (:P_YN != 'Y' or :P_YN is null) and :P_SELECT is null
    That fixed it.... I like null and I hate null
    Thanks for the reply

  • Select rows from the table which don't exist in another table

    Hi, in this relatively simple task I have some problem. I need to get the records from the T1 which don't exist in T2, based on some criteria.
    here is my query:
    select a.ordernum, sum(totchg), b.tracknum, rownum from T1 a, T2 b where 1=1 and a.ordernum not in( select ordernum from T2 ) and entrydate between to_date('06/23/2007','MM/dd/yyyy') and to_date('06/30/2007','MM/dd/yyyy') group by a.ordernum, b.tracknum, rownum
    it suppose to return me "TRACKNUM" empty, however it's being returned populated.
    I also tried :
    select a.ordernum, sum(totchg),b.tracknum, rownum from T1 a,
    T2 b where[b] not exists( select '1' from T2 where a.ordernum = b.ordernum )
    and entrydate between to_date('06/23/2007','MM/dd/yyyy') and to_date('06/30/2007','MM/dd/yyyy') group by a.ordernum, b.tracknum, rownum
    the results are the same.
    please advise.

    You are trying to get a returned value field from T2 when you just said that the
    records returned from Only T1 are not found in T2, therefore no T2 record to return.
    You only get T1 records where the Ordernum key is not found in T2.
    select ordernum, tracknum, rownum, sum(totchg)
    from T1
    where ordernum not in( select ordernum from T2 )
    and (entrydate between to_date('06/23/2007','MM/dd/yyyy') and
    to_date('06/30/2007','MM/dd/yyyy') )
    group by ordernum, tracknum, rownum

  • Change value of a field, based on another fiekd, before insert...

    I have this situation: I have to generate a code (this happens through a database function) on the moment a new record is saved. This code is based on another field of that record (parameter passed to the function). I (have to) use Apex 3, so I can't use functionality of Apex 4.
    So to be concrete: I have a registration program of books. Eacht book has a unique library code (this is not the PK). The labrary code is based on the year of publication (e.g. B2010-00035). So once a new book is entered, before saving, the year of publication (e.g. 2010) is checked, and throug a database function (e.g. f_get_new_library_code(2010) returns "B2010-00036") the library code has to be filled out.
    How can I do this on the best way, taking into account I can't use Dynamic Actions of Apex 4 (unfortunatly).

    Hi,
    If you had specified the type of Form the answer would have been more to the point !
    If its a single row form then you can write a OnSubmit Computation where in you call your function.
    If its a Tabular Form then you have to write a OnSubmit After Comp & Val process where you will iterate through the apex_application.g_f arrays and update the required arrays.
    Regards,

  • How do I autofill left to right (or copy/paste) from data that is up and down in another table?

    I have source data that is in a table as a column, and I would like to have it autofilled (simply copy/paste if need be) into a row in a separate table.  Is there an easy way to do this without doing each cell individually?

    Question asked and answered many times.
    What you ask for is named "Transpose a row" or "Transpose a column".
    Yvan KOENIG (VALLAURIS, France) lundi 29 août 2011 22:48:45
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.0
    My iDisk is : <http://public.me.com/koenigyvan>
    Please : Search for questions similar to your own before submitting them to the community

  • Assign value to field of table before calling function module

    hi,
    FM 'ABC' have some TABLES parameters.
    Before calling a function module 'ABC',i want to assign a value to one of the fields of the TABLES parameter.
    TAB1 is a name of parameter and field FLD1 is a name of the field of TAB1 which i want to update before calling 'ABC'.
    Thank you in advance.

    hi,
    1. store value in workarea
    tab1-fld1 = 'value'.
    2. append/modify the entry in tab1.
    append tab1.
    or
    modify tab1
    3. call your function module

  • How to create a element that contain a element generated in another document

    Hi,anybody.
    I want to create a element that contained a element generated in another document.The following is my coding:
    doc1 = new XMLDocument();
    ele1 = (XMLElement)doc1.createElement("AAA");
    doc2 = new XMLDocument();
    ele2 = (XMLElement)doc2.createElement("BBB");
    ele2.appendChild(doc2.createTextNode("bbb"));
    XMLNode ele = (XMLNode)ele2.cloneNode(true);
    ele1.appendChild(ele);
    but there is a DOMException,Node doesn't belong to the current document.
    Thanks in advance.
    null

    Hi Marc,
    it is currently not possible to check for values in other tables within different repositories (main tables).
    If you want to check for values in flat lookup tables, use the "Fields" menu in the expression editor. You will get sth like this:
    IS_NULL(Category.Item)
    whereas "Category" could be a lookup table (flat, hierarchy, taxonomy) and "Item" a field in it.
    Checking across qualified lookup tables is only possible in a very restricted manner.
    Hope that helps.
    Christian

  • Line item dimension wont insert sid values in infoobject sid table

    Hi all,
       I have a strange problem, whenever I load data into a cube which has a line item dimension on 0customer without first loading the master data I am getting inconsistency in RSRV saying that no corresponding DIMid exists in sid table.
    So there are Dimids in the fact table but the dimension table, which is same as the sid table in the the case of line item dimension, doesnt have them.
    Can someone explain me why is this happening?  I thought if a characteristic value doesnt exist in the master data but comes in through the transaction data it inserts the same in the sid table. 
    Is there a different rule for line item dimensions? Can someone point me to some OSS or documentation?
    thanks

    Thanks all..
    To clear up a few questions:
    1. What I mean by <i>"So there are Dimids in the fact table but the dimension table, which is same as the sid table in the the case of line item dimension, doesnt have them"</i> is:
    the line item dimension table /bic/D<cubename>9 which is really a view on the sid table for characteristic /bic/s<ch. name> does have all the sid values (or all the dim values) as the fact table.
    So fact table has more entries for that dimension than the sid table.
    2. Yes we are facing reporting errors where we cannot drill down by that infoobject and LISTCUBE doesnt show us any cube data when that characteristic is chosen for display.
    3. I have checked notes where it seems to be a RSRV bug but in our case it doesnt seem to be as observed in the actual table mentioned in #1
    Now it is apparent that I am right both from help.sap.com link and what I am observing that for line item dimensions master data HAS TO BE LOADED FIRST for the characteristics used as a line item.

  • How to create another table with an exisiting table

    Hi,
    I want to create another table on the top of an existing table, my existing table has few constraints and checks, i want to create another table which should copy all checks and constraints from existing table.
    for example;
    <p>
    create table temp
    </p>
    <p>
    (idx number primary key,
    </p>
    <p>
    publish varchar2(250) not null,
    </p>
    <p>
    address varchar2(250) not null,
    </p>
    <p>
    rent number check (rent &gt;=0))
    --<strong>Required output</strong>
    </p>
    <p>
    create table temp1
    </p>
    <p>
    as select * from temp
    </p>
    <p>
    where 1=2
    the structure of the table received as an output has the following structure:
    </p>
    <p>
    CREATE TABLE TEMP1
    </p>
    <p>
    </p>
    <p>
    IDX NUMBER,
    </p>
    <p>
    PUBLISH VARCHAR2(250 BYTE) NOT NULL,
    </p>
    <p>
    ADDRESS VARCHAR2(250 BYTE) NOT NULL,
    </p>
    <p>
    RENT NUMBER
    </p>
    <p>
    </p>
    <p>
    where i could not find primary key and check constraint but i can see not null check. Is there anyway that i could get the all checks when i create another table on the top of an existing table.
    </p>
    Best Regards,

    A CTAS (CREATE TABLE AS SELECT ...) probably isn't what you're looking for since that doesn't handle constraints.
    Depending on the Oracle version, you can probably use the DBMS_METADATA package to get the DDL for the table and then modify the DDL to create the copy, i.e.
      1* select dbms_metadata.get_ddl( 'TABLE', 'TEMP' ) from dual
    SQL> /
    DBMS_METADATA.GET_DDL('TABLE','TEMP')
      CREATE TABLE "SCOTT"."TEMP"
       (    "IDX" NUMBER,
            "PUBLISH" VARCHAR2(250) NOT NULL ENABLE,
            "ADDRESS" VARCHAR2(250) NOT NULL ENABLE,
            "RENT" NUMBER,
             CHECK (rent >=0) ENABLE,
             PRIMARY KEY ("IDX")
      USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255
      STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
      PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
      TABLESPACE "USERS"  ENABLE
       ) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
      STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
      PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
      TABLESPACE "USERS"You'd then just need to replace the "TEMP" with "TEMP1".
    Justin

Maybe you are looking for

  • Need Help Connecting Logitech Z560 to New Intel Imac

    I am a newly converted PC user. Like most of us, I am amazed by my new Imac. I have a Logitech 4.1 z560 speaker setup that I would try to use with the Imac, if possible. My problem is that the connection from the speaker "control center" is actually

  • Unwanted highlighting

    We've noticed that our Forms on 10g now have each record highlighted in blue. Our user does not want this as the client/server v6 Forms did not have them. I have tried changing the lookAndFeel and colorScheme applet parameters but to no avail. Can an

  • Re: we do not recognize your sign in details

    Few days ago I was kicked of my skype. Trying to log in again produced the same result: we do not recognize your sign in details. Meanwhile I created a new account, but lost important contacts. The problem is that I can not access registered email ac

  • HT1689 I forgot my security answers how do I reset them

    I forgot my security questions, How do I reset them?

  • Desktop.debug: exceptions messages

    Alex and Raju, i tried 2 sequence : 1) If i run the custom auth module (which is using a java Class in /etc/opt/SUNWps/desktop/classes), without adding the the classpath in jvm12.conf -> i get no error messages in both auth logs and desktop logs; Her