Creating a Trigger and some Database Design

Here is the scenario, we have the following tables
Orders, OrderDetails, Products, ProductsToInventory, Inventory, and InventoryDetails
Orders is where the orders are saved and their details are in OrderDetails (orderdetails has a column called Type and that type can either be a product, inventory, shipping, fee, so that we can distinguish what each one is in the order)
Products are the products we sell and ProductsToInventory refers each product to the inventory items required for it.
Inventory lists the the name, size, and weight of the item
then InventoryDetails stores the cost, original quantity received, and the current quantity (since the company receives different quantities of the same product at different pricing all the time)  (I would appreciate all the comments on this, this is
the best way I thought of doing this but if you have another way i'd appreciate it)
So that's the design, now we created a trigger that basically does this...
When an order is created and a PRODUCT is inserted into the the orderdetails, we will, using trigger, run the following query to insert the INVENTORY into the orderdetails
   INSERT INTO OrderDetails (...., OrderDetailPrice)
   SELECT ..., OrderDetailPrice?
    FROM inserted i INNER JOIN ProductToInventories pt
    ON i.productid = pt.id
    INNER JOIN Inventories inv
    ON pt.InventoryID = inv.InventoryID
    LEFT JOIN InventoryDetails idet
    ON inv.InventoryID = idet.InventoryDetailInventoryID
    WHERE OrderDetailType = "PRODUCT"
This works perfectly fine, however... for the price, we don't know what to do here, since the price is not in the inventory, the price is  under the inventorydetails and we will have to look up to that table to see which one has quantity > the quantity
needed here and then grab the price for that and then we need to update the quantity on that as well.

Here is the scenario, we have the following tables
Orders, OrderDetails, Products, ProductsToInventory, Inventory, and InventoryDetails
Orders is where .....
Good day TheSQLNewb,
I did not read more than I quote above... This is a starting of a nice story :-) but in the forum and in DBA's life we prefer to get DDL+DML instead of stories.
Please post queries to create the relevant tables (this is DDL by the way), and queries to insert some sample data (DML). with this information we will be able to reproduce the tables in our server and work on them.
Thanks :-)
  Ronen Ariely
 [Personal Site]    [Blog]    [Facebook]

Similar Messages

  • How can i create a new and tableless database using database configuration

    How can i create a new and tableless database using database configuration

    How can i create a new and tableless database using database configuration
    Just don't install the sample schemas. See the installation guide
    http://docs.oracle.com/cd/E11882_01/server.112/e10831/installation.htm
    Using the Database Configuration Assistant
    When you install Oracle Database with the Oracle Universal Installer, the sample schemas are installed by default if you select the Basic Installation option. Selecting the sample schemas option installs all five schemas (HR, OE, PM, IX, and SH) in the database. If you choose not to install the sample schemas at that time, you can add them later by following the instructions in section "Manually Installing Sample Schemas".
    Choose a custom install and don't install the sample schemas.
    All other schems/tables installed are REQUIRED by Oracle

  • Creating a question and answer database with un incremental question table

    Hello,
    i have a project which am suppose to create a database which will be Question and Answers.
    the Question are not to be increasing in the database but only the answers.
    exp:
    Question Table:
    Questions: have you slept well?. Do you have children?. and so on till 12 question.
    Answer Table:
    Answers : 1.yes, 2.no, 3.may be, 4.some how,
    and this Answer should be updated in the database with numbers for instant yes should be 3, no should be 0, may be should be 2 and some how should be 1.

    Related forum thread:
    http://stackoverflow.com/questions/4695227/how-to-structure-a-database-with-questions-and-answers
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Creating a simple and small DataBase..Please HELP

    I study Information Systems (MSc)..and I am taking a DataBase course that requires a Project to be done on a RDBMS..I decided to build the database using ORACLE 9i (on windows xp professional)..
    I want to use the Database Configuration Assistant to build the Database (easier than to build it manually)..but the Assistant requests from me to input some parameters that are somehow "new and strange" to me as a student..
    PLEASE I need the simplest and easiest parameter values to be input to the Assistant that enable me to build a tiny and simple DataBase that is adequete for educational purposes only (small project)..
    Also I need to know how to enter the DataBase after I create it..
    Thank you very much in advance..

    I study Information Systems (MSc)..and I am taking a DataBase course that requires a Project to be done on a RDBMS..I decided to build the database using ORACLE 9i (on windows xp professional)..
    I want to use the Database Configuration Assistant to build the Database (easier than to build it manually)..but the Assistant requests from me to input some parameters that are somehow "new and strange" to me as a student..
    PLEASE I need the simplest and easiest parameter values to be input to the Assistant that enable me to build a tiny and simple DataBase that is adequete for educational purposes only (small project)..
    Also I need to know how to enter the DataBase after I create it..
    Thank you very much in advance..

  • Create a standalone and portable database

    Until now, i have been coding my programs in visual basic 6, and i am used to create my desktop applications building an exe file and attaching a .dbm database beside it.
    That way, it was easy to port them to another computers.
    Now im trying to do something similar with java, and some people recommended me to use JavaDB - But i think i cannot achieve the same portability as i described i was using until now.
    Does anyone have any idea on how to do this?
    Thanks!

    Yes, JavaDB is another embeddable database. It's delivered with the JDK, if I remember correctly (never used it). Be aware that it's not installed with the JRE, however. So if you want to distribute your application, you'll have to distribute the JavaDB jar file as well.
    A third candidate would be H2.

  • Getting Started with Creating Mobile Apps and Websites with Design and Web Premium CS6 | Digital Design CS6 | Adobe TV

    Adobe Evangelist Paul Trani shows how to create apps and websites for multiple screens using Design & Web Premium CS6.
    http://adobe.ly/Iq676Z

    I have CS6.5 installed through the Adobe Application Manager, Creative Cloud account. There are  no PhoneGap sample pages under Mobile Started, only the ones labelled (Local). Where / how can I get these sample pages?

  • To create a folder and some subfolders in it using jsp

    Hai everyone,
    I am developing an auto responder application in which i need to organise the auto reponder lists in the best way.one idea for this maintainance is to create folders for each company and then organise the autoresponder list of that company in that particular folder. If needed there should be a possibility to create sub folders in it.
    So whenever someone wants to create a new auto responder he should have this option where he will be having a Browse button to create a new folder or to create in a subfolder in an already existing folder.
    I need this to be developed in jsp.
    Can anyone help me in this regard.

    First, JSP if for presenting data. It is not meant for doing this kind of stuff. JSP is server-side technology, and (assuming you want to create folders on the client-side) it's not going to be possible.
    I suppose there is some horribly nasty hacked ActiveX code that could pull this off, but Java by itself is secure. To allow a web application to access a person's file system is just craziness. Moreover, users are scared sh*tless to run ANY ActiveX scripts and most people that are tech savvy disable all ActiveX by default, so you have multiple problems here.
    My suggestion, do this in Swing using Java Web Start. Forget about JSP for this task.

  • Suggestion:  Create a Database Design Forum

    I recommend the creation of a new forum dealing exclusively with database design questions, such as setting Primary Keys, Unique constraints, Check constraints, Indexes, schema-creation scripts, etc. There is no forum devoted exclusively to this topic now and I feel it would be very helpful to the user community. It would certainly make searching for answers to design questions much easier.

    Billy  Verreynne  wrote:
    Prohan wrote:
    I don't agree there.
    1. How to create a relational model certainly IS relevant to Oracle, which is a RELATIONAL DBMS.Oracle also supports data warehousing (star schema designs), network/hierarchical designs, object-relational designs - or pretty much any data model that you may come up with. Calling it just a relational DBMS is incorrect.
    2. Your point that logical models are independent of specific technology is correct. What you're missing is that if a specific technology makes use of a certain foundational body of knowledge, that knowledge is a legitimate topic for a forum whose users use that specific technology.That is putting the cart in front of the horse IMO.
    I would rather see data modeling and logical database design being done in a way that is untainted with specific vendor implementations and technology used. There needs to be a clear line dividing the design from the implementation. If not, then design decisions can (and will) be made based not on the correct logical data modeling principles, but whether it can be "handled" by the technology. A design that is tainted like that, will always be less than optimal (especially as technology is continually evolving and changing).
    An OTN forum for database design will invariable be tainted with Oracle technology - and instead of learning sound data modeling fundamentals, a warped view of data modeling will be conveyed. Where doing abc will be acceptable (when it is not), because Oracle has feature xyz that can make the flawed design work (in a fashion).Excellent points. I think (or at least hope) such a forum would attract some number of pure theorists to straighten out the view. This might make for a lively forum, and might actually influence the real products, and might even get the cart on the right side of the horse.
    Hmmm, I guess I do sound hopelessly optimistic.

  • Logical Database design and physical database implementation

    Hi
    I am an ORACLE DBA basically and we started a proactive server dashboard portal ,which basically reports all aspects of our infrastructure (Dev,QA and Prod,performance,capacity,number of servers,No of CPU,decomissioned date,OS level,Database patch level) etc..
    This has to be done entirely by our DBA team as this is not externally funded project.Now i was asked to do " Logical Database design and physical Database
    implementation"
    Even though i know roughly what's that mean(like designing whole set of tables in star schema format) ,i have never done this before.
    In my mind i have a rough set of tables that can be used but again i think there is lot of engineering involved in this area to make sure that we do it properly.
    I am wondering you guys might be having some recommendations for me in the sense where to start?are there any documents online , are there any book on this topic?Are there any documents which explain this phenomena with examples ?
    Also exactly what is the difference between logical database design vs physical database implementation
    Thanks and Regards

    Logical database design is the process of taking a business or conceptual data model (often described in the form of an Entity-Relationship Diagram) and transforming that into a logical representation of that model using the specific semantics of the database management system. In the case of an RDBMS such as Oracle, this representation would be in the form of definitions of relational tables, primary, unique and foreign key constraints and the appropriate column data types supported by the RDBMS.
    Physical database implementation is the process of taking the logical database design and translating that into the actual DDL statements supported by the target RDBMS that will create the database objects in a target RDBMS database. This will generally include specific physical implementation details such as the specification of tablespaces, use of specialised indexing (bitmap, clustered etc), partitioning, compression and anything else that relates to how data will actually be physically stored inside the database.
    It sounds like you already have a physical implementation? If so, you can reverse engineer this implementation into a design tool such as SQL Developer Data Modeller. This will create a logical design by examining the contents of the Oracle data dictionary. Even if you don't have an existing database, Data Modeller is a good tool to use as a starting point for logical and even conceptual/business models.
    If you want to read anything about logical design, "An Introduction to Database Systems" by Date is always a good starting point. "Database Systems - A Practical Approach to Design, Implementation and Management" by Connolly & Begg is also an excellent reference.

  • Database design and pl/sql vs external procedures

    hi,
    My project involves predicting arrival time of a bus at a bus-stop, given statistical data of traffic patterns on the previous ‘n’(say 3) days, as well as the current location of the bus(latitude-longitude).
    Given current bus location, I derive my distance-until-destination bus-stop, which must be translated into time until arrival.
    Ive enlisted the triggers and procedures involved in making the prediction. Thse procedures especially the determination of perpendicular distances involve some complex trigonometric operations. I would like to know if my approach is correct and my database design is suited for the operations to b performed.
    Will it be more efficient to implement the procedures as external procedures or as pl/sql blocks
    This is my database design:
    LINKS ( a link is the road segment between adjacent bus-stops)
    LINK_ID                NUMBER      [PRIMARY-KEY]
    START_LATITUDE          NUMBER     
    START_LONGITUDE     NUMBER     
    START_STOP_ID          NUMBER
    END_LATITUDE          NUMBER
    END_LONGITUDE          NUMBER
    END_STOP_ID          NUMBER
    LINK_LENGTH          NUMBER
    BUS_ROUTE
    ROUTE_ID               NUMBER
    LINKS_ENROUTE          VARRAY(30) OF NUMBER
    STOPS_ENROOUTE          VARRAY(30) OF NUMBER
    TRACK(keeps track of current location of bus)
    BUS_ID           NUMBER          [PRIMARY-KEY]
    ROUTE          VARCHAR2(20)
    LATITUDE          NUMBER
    LONGITUDE          NUMBER
    TS               TIMESTAMP
    LINK_ID          NUMBER
    START_STOP     NUMBER
    END_STOP          NUMBER
    ARRIVAL_TIMES(actual arrival times of the bus, updated by track)
    BUS_ID           NUMBER     [PRIMARY-KEY]
    BUS_ROUTE          VARCHAR2(20)
    ARRIVAL          TIMESTAMP
    STOP_ID          NUMBER
    ETA (expected time of arrival)
    BUS_ID          NUMBER
    BUS_ROUTE          VARCHAR2(20)
    BUS_STOP_ID     NUMBER
    ARR_TIME          VARRAY(5) OF TIMESTAMP
    Triggers and procedures
    1)TRACK_TRIGGER
    On insert/update of track determine which link the us is currently on.
    Invoke a procedure that calculates perpendicular distance from current location to all links en-route (cursor on LINKS).
    Results are stored in a temporary table. Select the link-id of the tuple whose perpendicular distance is MINIMUM. This is the link the bus is currently on. Place link-id, start_stop_id and end_stop_id in corresponding row of TRACK.
    2)ARRIVAL_TRIGGER
    update ARRIVAL_TIMES.and store in ARRIVAL_TIMES that start-stop id with the time-stamp of the current track record.
    b)update ETA: Find the BUS-STOPS that come before the START_STOP of current track record. All these rows are deleted from the ETA tables, as the bus has already crossed these stops.
    3)Prediction Algorithm Procedure.
    Determine distance until destination for each STOP, 20 stops down from stop current location.
    Determine current avg. speed of the bus over a 2 hour window, by dividing total distance traveled by time taken.
    Calculate time-until arrival T1=current avg. speed * distance until destination
    From the records of previous ‘n’ days (say n=3) find those buses on the same route that were near the link the bus is currently on. Again determine avg speed over 2 hour window and calculate avg. speed.
    Calculate travel time T(i) = speed*distance until destination.     i.=2,3, 4…
    The final predicted arrival time is a weighted sum of all T(i).
    I hope Im not asking for too much, but the help would be greatly appreciated.
    Thankyou,
    Amina

    hello,
    actually i can manage ETA without a varray, since there will b a maxximum of 3 -4 values of expected arrival times at each stop. this can b done with separate columns.
    though i dont quite understand how lag() will help me...from what i understand lag() is to access values of previous rows. but in ETA table each element in the varray(if there is one) is going to be the expected arrival time of buses on a particular route at that particular stop, and is different from the arrival time at a previous stop(i.e.row).
    but for my other table BUS_ROUTE i have 2 varrays describing the links and stops enroute. in quite a few procedures i have to loop through these arrays and perform some calculations in every iteration is varray the best way 2 go, or nested tables?
    Thank you
    Amina
    As an aside, external procedures tend by their very
    nature to be slow - there's an overhead incurred
    each time we step outside the database. Therefore
    you really ought to avoid using a C extproc unless
    your calculations really cannot be done in PL/SQL or
    a Java Stored Procedure.
    Also, before you go down the VARRAY route you should
    consider the virues of analytic functions, notably
    [url=http://download-west.oracle.com/docs/cd/B1050
    1_01/server.920/a96540/functions56a.htm#83619]LAG()[/u
    rl]. I think you really ought to do some
    benchmarking of parformance before you start afdding
    denormalised columns like ETA. You may find the
    overhead in maintaining those columns exceeds their
    perceived benefits.
    Cheers, APC

  • Whats this error while creating a trigger

    HI ,
    I was creating a trigger and getting the following Error . What is this
    1 CREATE OR REPLACE TRIGGER TRG_AUDIT_LOGON AFTER
    2 LOGON ON DATABASE
    3 Declare
    4 v_sid v$session.sid%type ;
    5 v_serial v$session.serial# %type;
    6 v_username v$session.username%type;
    7 v_osuserid v$session.osuser%type;
    8 v_machinename v$session.machine%type;
    9 v_PROGRAM v$session.program%type;
    10 v_TERMINAL v$session.terminal%type;
    11 v_hostname v$instance.host_name%type;
    12 v_instance_name v$instance.instance_name%type;
    13 v_application_id v$database.dbid%type;
    14 v_logon_time date;
    15 v_Audit_tab_check varchar2(30);
    16 v_system_users_tab_check varchar2(30);
    17 v_sql_Audit_upload varchar2(1000) := 'INSERT INTO dbaoper.T_AUDIT (HOST_NAME, APPLICATION_ID, INSTANCE_NAME, SID, SERIAL#, USERNAME, OSUSERID, MACHINENAME, PROGRAM, TERMINAL, LOGON_TIME) VALUES (:v_hostname,:v_application_id,:v_instance_name, :v_sid, :v_serial, :v_username ,:v_osuserid,: v_machinename, :v_program,:v_TERMINAL,:v_logon_time ) ';
    18 type c_audit_cur_typ is ref cursor;
    19 C_Audit c_audit_cur_typ ;
    20 V_system_users_tab := 'T_SYSTEM_USERS';
    21 No_Audit_records Exception;
    22 Begin
    23 Select table_name into v_Audit_tab_check from dba_tables where owner='DBAOPER' and table_name='T_AUDIT';
    24 Select table_name into v_system_users_tab_check from dba_tables where owner='DBAOPER' and table_name='T_SYSTEM_USERS';
    25 Open c_Audit for ' SELECT sid, serial#, username, osuser, machine, program, terminal FROM v$session WHERE audsid = userenv (''''sessionid'''') and program not like ''''oracle@%J0%'''' and username not in (select * from dbaoper.' || V_system_users_tab||' ) and type!=''''BACKGROUND'''' ' ;
    26 Fetch c_Audit into v_sid, v_serial, v_username, v_osuserid, v_machinename,v_program,v_TERMINAL ;
    27 If c_Audit%Notfound then
    28 Raise No_Audit_records ;
    29 Else
    30 Select host_name, instance_name into v_hostname, v_instance_name from v$instance;
    31 select dbid into v_application_id from v$database;
    32 select sysdate into v_logon_time from dual;
    33 execute immediate v_sql_Audit_upload using v_hostname,v_application_id,v_instance_name,v_sid,v_serial,v_username,v_osuserid,v_machinename,v_program,v_TERMINAL,v_logon_time;
    34 end if;
    35 close C_Audit;
    36 exception
    37 when no_data_found then
    38 dbms_system.ksdwrt(2, ' ORA-20001 Audit tables T_AUDIT or T_SYSTEM_USERS not found Audit information is not being captured'
    39 );
    40 When No_Audit_records then
    41 dbms_output.put_line ('No Audit records to insert ');
    42* end;
    SQL> /
    Warning: Trigger created with compilation errors.
    SQL> sho err
    Errors for TRIGGER TRG_AUDIT_LOGON:
    LINE/COL ERROR
    18/20 PLS-00103: Encountered the symbol "=" when expecting one of the
    following:
    constant exception <an identifier>
    <a double-quoted delimited-identifier> table LONG_ double ref
    char time timestamp interval date binary national character
    nchar
    The symbol "<an identifier>" was substituted for "=" to
    continue.
    Thanks
    Pramod

    Hi
    I am sorry...i am getting the following error once trigger is created and one of the user is trying to connect....what might be the reason ?
    Enter user-name: test
    Enter password:
    ERROR:
    ORA-00604: error occurred at recursive SQL level 1
    ORA-00907: missing right parenthesis
    ORA-06512: at line 23
    Thanks
    Prmaod

  • Oracle Database Design Courses?

    Hi,
    I was searching around the Oracle website looking for
    some Database Design courses, couldn't find anything.
    Anyone know if this type of course is available, if not
    through Oracle then with some other company?
    TIA,
    Rick.

    Jens I found a few good links in there...I was trying to
    find if there was a certification track offered in
    DB Design? I see a lot of instructor led classes most
    of them only 2-3 days long.

  • How to create a Dir and files within it?

    Hi all ,
    I need to create a Dir and some sample files within it for some testing purpose,can any body tell me how to do it?(I follow al11 GUI options but its giving some error)
    Or
    Is there any FM by which we can do it directly to application server????
    Its urgent requirement..
    Thanx in advance

    to create a file in appl server you have to use open dataset and close data set..
    see the sample code
    REPORT zanid_test MESSAGE-ID zz .
    parameters:  FULLPATH(128) obligatory lower case
                          default 'E:\usr\sap\put\file.txt'.
    *you change the appl sever path as per your config.
    DATA : BEGIN OF list_asc OCCURS 0,
            msg(300) TYPE c,
           END OF list_asc.
    start-of-selection.
    *---populating data
    list_asc-msg = 'abcdefghijkl'. "your sample data
    append list_asc.
    list_asc-msg = 'faagoaagiagig'. "your sample data
    append list_asc.
    OPEN DATASET fullpath FOR OUTPUT IN TEXT MODE.
    LOOP AT LIST_ASC.
          TRANSFER  LIST_ASC-MSG TO fullpath.
          CLEAR LIST_ASC-MSG.
    ENDLOOP.
    CLOSE DATASET fullpath.
    now if you go to appl server , you will find that file in that specified path..
    to create a directory yu can go to transaction AL11 and click the 'konfigurieren'button, you then you can specify the directory attibutes to create a directory
    and to load a file from your loacl pc to appl server you can use transaction CG3Y also, instead of the abap code.
    plz rewrad points if it helps you.

  • Good database design and modelling books

    Hi ,
    I need to work on designing a database from the scratch by creating logical database design and then physical database design.I'm new to database design.
    Can someone please point me to some good database design and modelling related books /tutorials.
    Regards,
    Bharath.

    bharathDBA wrote:
    Hi Girish Thanks for the information.
    I would definitely look into this book later.
    I don't mind paying any amount of money,if that book gives me the knowledge I want.
    As this book is international edition,for shipping it is taking 8-10 business days and by that time I need to complete designing my database and probably I might need to some other book.
    Is this a school assignment? I hope so. Referring back to your opening statement "I need to work on designing a database from the scratch by creating logical database design and then physical database design.I'm new to database design." I can only say that database design is a very big subject. If you are starting from a position of no knowledge at all, I'm afraid there is nothing that is going to give you the knowledge you need in the time frame you have. I will say you need to start by learning the rules of Data Normalization. Make your logical design Third Normal Form. Good can be your friend. There is actually a pretty good write-up on Data Normalization on Wikipedia.

  • Help me in creating a Trigger for Insert and Update Options

    Hi
    Please help me in creating a Trigger .
    My requirement is that after insert or update on a Table , i want to fire an event .
    I have started this way ,but doesn't know how to fully implement this .
    say i have a dept table
    CREATE TRIGGER DepartmentTrigger
    AFTER INSERT ON Dept
    BEGIN
    INSERT INTO mytable VALUES("123","Kiran");
    END DepartmentTrigger;
    Please tell me how can i put the Update option also .
    Thanks in advance .

    Please tell me how can i put the Update option also .Add "Or Update". ;-)
    Here are a few suggestions, but you definitely need to refer to the manual page that the previous poster suggested.
    CREATE OR REPLACE TRIGGER DepartmentTrigger
    AFTER INSERT Or Update ON Dept
    BEGIN
    INSERT INTO mytable VALUES(:new.Dept,'DEPT ADDED OR CHANGED');
    END DepartmentTrigger;
    The "Or Replace" means you can replace the trigger while you're developing without having to type in a drop statement every time. Just change and rerun your script, over and over until you get it right.
    Adding "Or Update" or "Or Delete" makes the trigger fire for those events too. Note, you may want seperate triggers in different scripts and with different names for each event. You have to decide if your design really does the same thing whether it's an insert or an update.
    :new.Dept is how you would refer to the changed vale of the Dept column (:old.Dept is the prior value). I changed the double quotes on the string in the VALUES clause to single quotes.
    Andy

Maybe you are looking for