Insert into a table excluding duplicates of a selected column

I have mytable:
IDNO
Item
Date
Level
1
X24
12/23/13 10:41
22996
2
X24
12/23/13 10:41
22996
3
X24
12/23/13 9:21
23256
4
X24
12/23/13 9:21
23256
5
X24
12/23/13 9:22
23256
6
X24
12/23/13 9:22
23256
7
X24
12/23/13 9:22
22916
that is a result of INSERT i.e.,
INSERT INTO myTABLE(Item,[Date],[Level])
values('X24','12/23/13 :22','22916')
I want the INSERT to exclude the duplicate level defined as the previous level in a selected column [Level]. This would avoid having to 'view' the table using:
SELECT
i.IDNO,i.[Date],i.[Level]
FROM
mytable
i
INNER
JOIN
mytable
d
ON
d.IDNO
=
i.IDNO-1
WHERE
i.[Level]
<>
d.[Level]
IDNO is an identity column.
How can this INSERT be achieved without the overheads? 

Quite helpful comments particularly the ISO- 11179 and the design elements that can prevent the problem in the first instance. My apologies with regards to my impolite post omitting the DDL.  It is a small procedure and [Date] and [Level] can be accommodated
by the server but are bad habits. My efforts to control the data input were in vain as the data was not from a software conducive to such controls. Because of the high frequency volume of the data, (suggested by the time-stamps with milliseconds cut), any
effort to have 'The data... cleaned in a presentation/input layer ' would be futile.  The suggestions of  yourself
and Erland Sommarskog, SQL Server MVP, [email protected], of a UNIQUE constraint to deal with the problem
underscores the importance of design even in the 'smallest' of procedures. 
This worked:
drop table Foobar
CREATE TABLE Foobar
(item_name CHAR(5) NOT NULL, 
 foo_timestamp DATETIME2(0) NOT NULL
  CHECK (foo_timestamp 
    = DATEADD(MINUTE, DATEDIFF(MINUTE, '2000-01-01', foo_timestamp),
     '2000-01-01')),
 water_level INTEGER NOT NULL, -- why not be silly? 
 PRIMARY KEY (item_name,foo_timestamp, water_level));
INSERT INTO Foobar
VALUES
('X24', '2013-12-23 10:41:00', 22996), 
-- ('X24', '2013-12-23 10:41:00', 22996), rejected by DDL!!
-- ('X24', '2013-12-23 09:21:00', 23256), rejected by DDL!!
('X24', '2013-12-23 09:21:00', 23256), 
('X24', '2013-12-23 09:22:00', 23256), 
-- ('X24', '2013-12-23 09:22:00', 23256), rejected by DDL!!
('X24', '2013-12-23 09:22:00', 22916);
select *
from Foobar
item_name foo_timestamp
water_level
X24   2013-12-23 09:21:00
23256
X24   2013-12-23 09:22:00
22916
X24   2013-12-23 09:22:00
23256
X24   2013-12-23 10:41:00
22996

Similar Messages

  • How to INSERT INTO Shema1.Table (F1,F2...) SELECT F1,F2 FROM Shema2.Table

    I am trying to implement a stored procedure witch should copy date from shema1.table into shema2.table. Tables in both shemas are identical! I need an elegant solution which is implemented as a store procedure or package. Can someone please help me!? Thanx!

    Instead of PUBLIC.OAP_WORK_NARUDZBE
    Try OAP_WORK_NARUDZBE.
    And post the full error that you get.
    You can test it with SELECT * FROM OAP_WORK_NARUDZBE from your session, and also from your procedure. There is probably a problem with underlying grants, not with the synonym itself.
    After rereading the original requirement, I don't understand why we are talking about synonyms anyway.
    Make sure you can select from the table in Schema2. To be aber to do this INSIDE a stored procedure you need to GRANT the right DIRECTLY to the user. That means:
    Schemauser1 (OAP_WORK) must do: GRANT SELECT ON narudzbe TO Schemauser2Do not grant it to a role.
    Schemauser2 (OAP_DATA) can then INSERT INTO narudzbe (...) SELECT ... FROM Schemauser1.narudzbe inside the procedure.
    Message was edited by:
    Sven Weller

  • Record not inserting into the table through Forms 10g

    Hi all,
    I have created a form in 10g(10.1.2.0.2) based on just one table that has 4 columns(col1, col2, col3, col4).
    Here col1, col2 and col3 are VARCHAR2 and col4 is date and all the columns are not null columns(There are no primary and foriegn key constrains, which means duplicates are allowed).
    My form contains 2 blocks where block 1 has one text item (col1) and 3 buttons (Delete, Save, Exit).
    And block2 is a database block and has col2,col3,col4 which are in tabluar layout frame displaying 10 records.
    When the form is opened the cursor has to be in block1.col1 for querrying. Here i enter a value in col1, and then when I click on col2 in the block2, then I put execute_query in new_block_instance of block2, which displays the records.
    The block2 properties are not updatable, insertable and query is allowed.
    Everything is working good until here. But here in the block2 when I want to insert another record into the table, by navigating all the way down to the last empty record and entering the new values for col2, col3 and col4 And then Ctrl+S will display the message "*FRM-40400: Transaction complete: 1 record applied and saved.*" But actually the record is not inserted into the table.
    I also disabled the col4 by setting the Enabled property to No, since while inserting new record the date have to be populated into it and it shouldnt be changed by the user. And im populating the sysdate into the new record by setting Intial Value property to *$$DATE$$*.
    And another requirement which I could not work arround here is that, the col3 also should be populated with the username of the user while inserting.
    please help me...

    Hi Sarah,
    I do not want to update the existing record. So I kept Udate Allowed to No in property palette for the items in block2.
    Do I have to do this property at block level also?
    I'm inserting a new record here.
    Edited by: Charan on Sep 19, 2011 8:48 AM

  • How can I insert into a table other than the default table in a form

    Hi,
    I want to insert into a table with some fields value of a form of another table. I have written insert code On successful submission of that form, but after submit it gives the following error
    An unexpected error occurred: ORA-06502: PL/SQL: numeric or value error (WWV-16016)
    My code is like this
    declare
    l_trn_id number;
    l_provider_role varchar2(3);
    l_provider_id varchar2(10);
    begin
    l_trn_id := p_session.get_value_as_number(p_block_name=>'DEFAULT',p_attribute_name=>'A_TRANSACTION_ID');
    l_provider_id := p_session.get_value_as_varchar2(p_block_name=>'DEFAULT',p_attribute_name=>'A_PROVIDER1');
    l_PROVIDER_ROLE := p_session.get_value_as_varchar2(p_block_name=>'DEFAULT',p_attribute_name=>'A_PROVIDER_ROLE1');
    if (l_provider_role is not null) and (l_provider_id is not null) then
    insert into service_provider_trans_records(service_provider_id,transaction_id,role_type_id)
    values(l_provider_id, l_trn_id, l_provider_role);
    commit;
    end if;
    end;
    Where 'PROVIDER1' and 'PROVIDER_ROLE1' are not table fields.
    How can do that or why this error comes ? Any idea?
    Thanks
    Sumita

    Hi,
    When do you get this error? Is it while running or while creating the form.
    Here is a sample code which inserts a non-database column dummy into a table called dummy. This is done in successful procedure.
    declare
    l_dummy varchar2(1000);
    begin
    l_dummy := p_session.get_value_as_varchar2(p_block_name=>'DEFAULT',
    p_attribute_name=>'A_DUMMY');
    insert into sjayaram903_1g.dummy values(l_dummy);commit;
    end;
    Please check in your case if the size of the local variable is enough to hold the values being returned.
    Thanks,
    Sharmila

  • Inserting into a table which is created "on the fly" from a trigger

    Hello all,
    I am trying to insert into a table from a trigger in Oracle form. The table name however, is inputted by the user in am item form.
    here is what the insert looks like:
    insert into :table_name
    values (:value1, :value2);
    the problem is that forms does not recognize ::table_name. If I replace :table_name with an actual database table, it works fine. However, I need to insert to a table_name based from oracle form item.
    By the way, the table|_name is built on the fly using a procedure before I try to insert into it.
    Any suggestion on how can I do that? My code in the trigger is:
    declare
    dm_drop_tbl(:table_name,'table) // a call to an external procedure to drop the table
    dm_create_tbl(:table_name,'att1','att2');
    insert into :table_name
    values (:value1, :value2);
    this give me an error:
    encounter "" when the symbol expecting one.....

    Hi ,
    You should use the FORMS_DDL built_in procedure. Read the on-line documentation of forms ...
    Simon

  • Problem while inserting into a table which has ManyToOne relation

    Problem while inserting into a table *(Files)* which has ManyToOne relation with another table *(Folder)* involving a attribute both in primary key as well as in foreign key in JPA 1.0.
    Relevent Code
    Entities:
    public class Files implements Serializable {
    @EmbeddedId
    protected FilesPK filesPK;
    private String filename;
    @JoinColumns({
    @JoinColumn(name = "folder_id", referencedColumnName = "folder_id"),
    @JoinColumn(name = "uid", referencedColumnName = "uid", insertable = false, updatable = false)})
    @ManyToOne(optional = false)
    private Folders folders;
    public class FilesPK implements Serializable {
    private int fileId;
    private int uid;
    public class Folders implements Serializable {
    @EmbeddedId
    protected FoldersPK foldersPK;
    private String folderName;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "folders")
    private Collection<Files> filesCollection;
    @JoinColumn(name = "uid", referencedColumnName = "uid", insertable = false, updatable = false)
    @ManyToOne(optional = false)
    private Users users;
    public class FoldersPK implements Serializable {
    private int folderId;
    private int uid;
    public class Users implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer uid;
    private String username;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "users")
    private Collection<Folders> foldersCollection;
    I left out @Basic & @Column annotations for sake of less code.
    EJB method
    public void insertFile(String fileName, int folderID, int uid){
    FilesPK pk = new FilesPK();
    pk.setUid(uid);
    Files file = new Files();
    file.setFilename(fileName);
    file.setFilesPK(pk);
    FoldersPK folderPk = new FoldersPK(folderID, uid);
         // My understanding that it should automatically handle folderId in files table,
    // but it is not…
    file.setFolders(em.find(Folders.class, folderPk));
    em.persist(file);
    It is giving error:
    Internal Exception: java.sql.SQLException: Field 'folderid' doesn't have a default value_
    Error Code: 1364
    Call: INSERT INTO files (filename, uid, fileid) VALUES (?, ?, ?)_
    _       bind => [hello.txt, 1, 0]_
    It is not even considering folderId while inserting into db.
    However it works fine when I add folderId variable in Files entity and changed insertFile like this:
    public void insertFile(String fileName, int folderID, int uid){
    FilesPK pk = new FilesPK();
    pk.setUid(uid);
    Files file = new Files();
    file.setFilename(fileName);
    file.setFilesPK(pk);
    file.setFolderId(folderId) // added line
    FoldersPK folderPk = new FoldersPK(folderID, uid);
    file.setFolders(em.find(Folders.class, folderPk));
    em.persist(file);
    My question is that is this behavior expected or it is a bug.
    Is it required to add "column_name" variable separately even when an entity has reference to ManyToOne mapping foreign Entity ?
    I used Mysql 5.1 for database, then generate entities using toplink, JPA 1.0, glassfish v2.1.
    I've also tested this using eclipselink and got same error.
    Please provide some pointers.
    Thanks

    Hello,
    What version of EclipseLink did you try? This looks like bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=280436 that was fixed in EclipseLink 2.0, so please try a later version.
    You can also try working around the problem by making both fields writable through the reference mapping.
    Best Regards,
    Chris

  • Diffrence between backend insert and front end insert into a table.

    I am developing a conversion program for tax exemption. For this program only ZX_EXEMPTIONS table is used to populate the data and we got confirmation from Oracle also regarding this.For inserting the data into this table we are taking the max of tax_exemption_id which is pk for this table and adding one to it and inserting into the table. But problem here is after inserting from back end we are not able to insert from front end.
    It seems backend data is holding the tax_exemption_id which is suppose to reserve by front end data.Please explain the different behavior of populating of tax_exemption_id from front end and back end.

    Hi,
    i think the problem is that you are using max-value + 1 for tax_exemption_id. But as ZX_EXEMPTIONS is using sequence ZX_EXEMPTIONS_S
    for primary key generation, you encounter situation that you are increasing PK Id for this table without increasing sequence value.
    When trying to insert rows from front end - which probably uses sequence value - it tries to use a sequence value already used by your backend
    process (which generated it by Maxvalue + 1) and would then encounter a primary key violation.
    I think you should use sequence mentioned above to generate your PK Ids in backend process as well. And before doing so, check current value
    of ZX_EXEMPTIONS_S, as you might need to rebuild the sequence in order to select nextval sucessfully for both frontend and backend.
    Regards

  • How can I get a count at the same time I am inserting into another table

    I have a requirement where I have to find out the count(number of records inserted into another table) at the same time I insert into the table:
    Like
    I am copying records from table B to A, while doing this I have to find out how many records I've inserted since I need this count in subsequent steps
    INSERT INTO A
    SELECT * FROM B
    how can I store the count into any variable while doing above statement
    Please advice

    No, Warren that doesn't work!
    SQL> set serveroutput on
    SQL> declare
      2     vCtr  number := 0;
      3  begin
      4     insert into emp2
      5     select * from emp;
      6
      7     select count(*)
      8       into vCtr
      9       from emp2;
    10
    11     dbms_output.put_line('rows created '||to_char(vCtr));
    12  end;
    13  /
    rows created 15
    PL/SQL procedure successfully completed.
    SQL> declare
      2     vCtr  number := 0;
      3  begin
      4     insert into emp2
      5     select * from emp;
      6
      7     select count(*)
      8       into vCtr
      9       from emp2;
    10
    11     dbms_output.put_line('rows created '||to_char(vCtr));
    12  end;
    13  /
    rows created 30
    PL/SQL procedure successfully completed.
    SQL>

  • How to extract data from xml and insert into Oracle table

    Hi,
    I have a large xml file. which will have hundreds of the following transaction tags having column names and there values.
    There is a table one of the schema with coulums "actualCostRate","billRate"....etc.
    I need to extract the values of these columns and insert into the table
    <Transaction actualCostRate="0" billRate="0" chargeable="1" clientID="NikuUK" chargeCode="LCOCD1" externalID="L-RESCODE_UK1-PROJ_UK_CNT_GBP-37289-8" importStatus="N" projectID="TESTPROJ" resourceID="admin" transactionDate="2002-02-12" transactionType="L" units="11" taskID="5017601" inputTypeCode="SALES" groupId="123" voucherNumber="ABCVDD" transactionClass="ABCD"/>
    <Transaction actualCostRate="0" billRate="0" chargeable="1" clientID="NikuEU" chargeCode="LCOCD1" externalID="L-RESCODE_US1-PROJ_EU_STD2-37291-4" importStatus="N" projectID="TESTPROJ" resourceID="admin" transactionDate="2002-02-04" transactionType="L" units="4" taskID="5017601" inputTypeCode="SALES" groupId="124" voucherNumber="EEE222" transactionClass="DEFG"/>

    Re: Insert from XML to relational table
    http://www.google.ae/search?hl=ar&q=extract+data+from+xml+and+insert+into+Oracle+table+&btnG=%D8%A8%D8%AD%D8%AB+Google&meta=

  • How to insert into a table with a nested table which refer to another table

    Hello everybody,
    As the title of this thread might not be very understandable, I'm going to explain it :
    In a context of a library, I have an object table about Book, and an object table about Subscriber.
    In the table Subscriber, I have a nested table modeling the Loan made by the subscriber.
    And finally, this nested table refers to the Book table.
    Here the code concerning the creation of theses tables :
    Book :
    create or replace type TBook as object
    number int,
    title varchar2(50)
    Loan :
    create or replace type TLoan as object
    book ref TBook,
    loaning_date date
    create or replace type NTLoan as table of TLoan;
    Subscriber :
    create or replace type TSubscriber as object
    sub_id int,
    name varchar2(25)
    loans NTLoan
    Now, my problem is how to insert into a table of TSubscriber... I tried this query, without any success...
    insert into OSubscriber values
    *(1, 'LEVEQUE', NTLoan(*
    select TLoan(ref(b), '10/03/85') from OBook b where b.number = 1)
    Of course, there is an occurrence of book in the table OBook with the number attribute 1.
    Oracle returned me this error :
    SQL error : ORA-00936: missing expression
    00936. 00000 - "missing expression"
    Thank you for your help

    1) NUMBER is a reserved word - you can't use it as identifier:
    SQL> create or replace type TBook as object
      2  (
      3  number int,
      4  title varchar2(50)
      5  );
      6  /
    Warning: Type created with compilation errors.
    SQL> show err
    Errors for TYPE TBOOK:
    LINE/COL ERROR
    0/0      PL/SQL: Compilation unit analysis terminated
    3/1      PLS-00330: invalid use of type name or subtype name2) Subquery must be enclosed in parenthesis:
    SQL> create table OSubscriber of TSubscriber
      2  nested table loans store as loans
      3  /
    Table created.
    SQL> create table OBook of TBook
      2  /
    Table created.
    SQL> insert
      2    into OBook
      3    values(
      4           1,
      5           'No Title'
      6          )
      7  /
    1 row created.
    SQL> commit
      2  /
    Commit complete.
    SQL> insert into OSubscriber
      2    values(
      3           1,
      4           'LEVEQUE',
      5           NTLoan(
      6                  (select TLoan(ref(b),DATE '1985-10-03') from OBook b where b.num = 1)
      7                 )
      8          )
      9  /
    1 row created.
    SQL> select  *
      2    from  OSubscriber
      3  /
        SUB_ID NAME
    LOANS(BOOK, LOANING_DATE)
             1 LEVEQUE
    NTLOAN(TLOAN(000022020863025C8D48614D708DB5CD98524013DC88599E34C3D34E9B9DBA1418E49F1EB2, '03-OCT-85'))
    SQL> SY.

  • How to insert into 2 tables from the same page (with one button  link)

    Hi,
    I have the following 2 tables....
    Employees
    emp_id number not null
    name varchar2(30) not null
    email varchar2(50)
    hire_date date
    dept_id number
    PK = emp_id
    FK = dept_id
    Notes
    note_id number not null
    added_on date not null
    added_by varchar2(30) not null
    note varchar2(4000)
    emp_id number not null
    PK = note_id
    FK = emp_id
    I want to do an insert into both tables via the application and also via the same page (with one button link). I have made a form to add an employee with an add button - adding an employee is no problem.
    Now, on the same page, I have added a html text area in another region, where the user can write a note. But how do I get the note to insert into the Notes table when the user clicks the add button?
    In other words, when the user clicks 'add', the employee information should be inserted into the Employees table and the note should be inserted into the Notes table.
    How do I go about doing this?
    Thanks.

    Hi,
    These are my After Submit Processes...
    After Submit
    30     Process Row of NOTES     Automatic Row Processing (DML)     Unconditional
    30     Process Row of EMPLOYEES     Automatic Row Processing (DML)     Unconditional
    40     reset page     Clear Cache for all Items on Pages (PageID,PageID,PageID)     Unconditional
    40     reset page     Clear Cache for all Items on Pages (PageID,PageID,PageID)     Unconditional
    40     reset page     Clear Cache for all Items on Pages (PageID,PageID,PageID)     Unconditional
    40     reset page     Clear Cache for all Items on Pages (PageID,PageID,PageID)     Unconditional
    50     Insert into Tables     PL/SQL anonymous block     Conditional
    My pl/sql code is the same as posted earlier.
    Upon inserting data into the forms and clicking the add button, I get this error...
    ORA-06550: line 1, column 102: PL/SQL: ORA-00904: "NOTES": invalid identifier ORA-06550: line 1, column 7: PL/SQL: SQL Statement ignored
         Error      Unable to process row of table EMPLOYEES.
    Is there something wrong with the pl/sql code or is it something else?

  • Fetch data from one table and insert into two tables in desired format

    I have similar to the following data in a table and it is not normalized. The groupID is being used to group two records of similar nature.
    DECLARE @OldDoc TABLE (oldDocID INT, groupID INT, deptID INT)
    INSERT INTO @OldDoc (oldDocID, groupID) VALUES (1, NULL, 111),(2,NULL,111),(3,1,111),(4,NULL,333),(5,1,222),(6,NULL,333),(7,2,222),(8,2,333),(9,NULL,111),(10,3,222),(11,NULL,333),(12,3,444)
    I need to process the data from the above table (@OldDoc) and write into two new tables (@NewDoc and @NewDocGroup) as follows.
    oldDocID should be stored as newDocID when inserting to @NewDoc table. Only records with groupID NULL and one record (first one) per group should be considered (For example, oldDocID 5 is not considered as 3 and 5 belong to the same groupID 1) for insertion. 
    DECLARE @NewDoc TABLE (newDocID INT)
    INSERT INTO @NewDoc (newDocID) VALUES (1),(2),(3),(4),(6),(7),(9),(10),(11)
    All records from @OldDoc should be considered for insertion into @NewDocGroup table. OldDocID is inserted as NewDocID and deptID is as-is. Instead of groupID, the ID of the first record in the 
    group should be considered as parentNewDocID (For example, 3 is considered as parentNewDocID for newDocID 5 as 3 and 5 belong to the same groupID in @OldDoc table) for the newDocID.
    DECLARE @NewDocGroup (newDocID INT, parentNewDocID INT, deptID INT)
    INSERT INTO @NewDocGroup (newDocID, parentNewDocID, deptID) VALUES (1,1,111),(2,2,111),(3,3,111),(4,4,333),(5,3,222),(6,6,333),(7,7,222),(8,7,333),(9,9,111),(10,10,222),(11,11,333),(12,10,444)
    How do I accomplish the above using SQL ? Thanks for the help.

    >> I have similar to the following data in a table and it is not normalized. The group_id is being used to group two records [sic] of similar nature. <<
    Rows are not records. Tables have to have a key by definition. You do not do math with identifiers, so they should not be numeric. Let's ignore that error for now. In short, you are posting garbage. If you had followed Forum Netiquette, would you have posted
    this? 
    CREATE TABLE Old_Documents
    (old_doc_id INTEGER NOT NULL PRIMARY KEY, 
     group_id INTEGER, 
     dept_nbr INTEGER NOT NULL
       REFERENCES Departments (dept_nbr));
    INSERT INTO Old_Documents(old_doc_id, group_id, dept_nbr) 
    VALUES  (1, NULL, 111), 
    (2, NULL, 111), 
    (3, 1, 111), 
    (4, NULL, 333), 
    (5, 1, 222), 
    (6, NULL, 333), 
    (7, 2, 222), 
    (8, 2, 333), 
    (9, NULL, 111), 
    (10, 3, 222), 
    (11, NULL, 333), 
    (12, 3, 444);
    >> I need to process the data from the above table (Old_Documents) and write into two new tables (New_Documents and New_Documents_Groups) as follows. <<
    Just like punch cards and mag tape data processing! Being old and being new are a status, not another kind of entity. But that is how mag tapes work. And you even use the verb "fetch" from tape files. This design flaw is called  attribute splitting.
    Do you have a Male_Personnel and Female_Personnel table? NO! It is just Personnel! 
    >> old_doc_id should be stored as new_doc_id when inserting to New_Documents table. Only records [sic] with group_id NULL and one record [sic] (first [sic; no ordering in a table] one) per group should be considered (For example, old_doc_id 5 is not considered
    as 3 and 5 belong to the same group_id =1) for insertion. <<
    Think about your punch card mindset. Why did you physically materialize that redundant New_Documents table? Let me answer that: this is how you work with punch cards! In SQL we use a VIEW:
    CREATE VIEW New_Documents (new_doc_id)
    AS 
    SELECT old_doc_id 
      FROM Old_Documents;
    >> All records [sic] from Old_Documents should be considered for insertion into New_Documents_Groups table. The old_doc_id is inserted as new_doc_id and dept_nbr is as-is. Instead of group_id, the ID [sic: which identifier??] of the first [sic: tables
    have no ordering like a deck of punch cards] record [sic] in the group should be considered as parent_new_doc_id (For example, 3 is considered as parent_new_doc_id for new_doc_id 5 as 3 and 5 belong to the same group_id in Old_Documents table) for the new_doc_id.
    <<
    Why not use 5 as the parent? My guess is that you are trying to form equivalence classes. See:
    https://www.simple-talk.com/content/print.aspx?article=2020
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Fetch data from two tables and insert into one table

    I have similar to the following data in two tables (@Plant, @PlantDirector) and need to consolidate into one table (@PlantNew) as follows.
    DECLARE @Plant TABLE (PlantID INT, PlantName VARCHAR(100))
    INSERT INTO @Plant (PlantID, PlantName) VALUES (1, 'Name One'),(2, 'Name Two'),(3, 'Name Three'),(4, 'Name Four'),(5, 'Name Five'),(6, 'Name Six')
    Director data for the Plants exist in the following table. Assistant value 1 means Assistant Director and 0 means Director. 
    Data exists only for subset of plants and a Plant may have one or both roles.
    DECLARE @PlantDirector TABLE (PlantID INT, PlantDirectorID INT, Assistant bit)
    INSERT INTO @PlantDirector (PlantID, PlantDirectorID, Assistant) VALUES (2, 111, 1),(2, 222, 0),(4, 333, 0),(6,444,1)
    The above data needs to be inserted into one table (@PlantNew) as follows: 
    PlantID in @Plant table is IDENTITY value and needs to be inserted as-is into this table.
    PlantDirExists will get a value of 1 if at least one record exists in @PlantDirector table for a PlantID. PlantAssistantDirID and PlantDirID should be set to the corresponding PlantDirID or NULL appropriately depending on the data.
    DECLARE @PlantNew TABLE (PlantID INT, PlantName VARCHAR(100), PlantDirExists bit, PlantAssistantDirID INT, PlantDirID INT)
    INSERT INTO @PlantNew (PlantID, PlantName, PlantDirExists, PlantAssistantDirID, PlantDirID)
    VALUES (1, 'Name One', 0, NULL, NULL),(2, 'Name Two', 1, 111, 222),(3, 'Name Three', 0, NULL, NULL),(4, 'Name Four', 1, NULL, 333),(5, 'Name Five', 0, NULL, NULL),(6, 'Name Six',1, 444, NULL)
    How do I achieve the above using SQL ? Thanks.

    like this
    INSERT @PlantNew  (PlantID, PlantName, PlantDirExists, PlantAssistantDirID, PlantDirID) 
    SELECT p.PlantID,
    p.PlantName,
    CASE WHEN pd.PlantID IS NULL THEN 0 ELSE 1 END,
    PlantAssistantDirID,
    PlantDirID
    FROM @Plant p
    LEFT JOIN (SELECT PlantID,
    MAX(CASE WHEN Assistant = 1 THEN PlantDirectorID END) AS PlantAssistantDirID,
    MAX(CASE WHEN Assistant = 0 THEN PlantDirectorID END) AS PlantDirID
    @PlantDirector
    GROUP BY PlantID)pd
    ON pd.PlantID = p.PlantID
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs
    You're missing a FROM
    insert into @PlantNew
    SELECT p.PlantID,
    p.PlantName,
    CASE WHEN pd.PlantID IS NULL THEN 0 ELSE 1 END,
    PlantAssistantDirID,
    PlantDirID
    FROM @Plant p
    LEFT JOIN (SELECT PlantID,
    MAX(CASE WHEN Assistant = 1 THEN PlantDirectorID END) AS PlantAssistantDirID,
    MAX(CASE WHEN Assistant = 0 THEN PlantDirectorID END) AS PlantDirID
    from @PlantDirector
    GROUP BY PlantID)pd
    ON pd.PlantID = p.PlantID

  • Can select, but cannot insert into oracle tables using php.

    I am having trouble inserting data into a tables in oracle using PHP. I can insert into the tables using baninst1, but nothing else. I can't even insert using the tables' owner. Every time I try I get the ORA-00492 error of table or view does not exist. However, I can run a select statement just fine. So far, baninst1 is the only user that can actually do inserts. I've triple checked all the table grants and everything is fine. Also, I can copy/paste the exact insert statement into SQL*Plus and it works with the correct user. It doesn't have to be baninst1. I've tried everything I can think of. I've tried putting the table name in quotes, adding the schema name to the table, checking public synonyms, but everything appears to be ok. I would greatly appreciate any suggestions others may have.
    I'm using PHP 5.2.3 with an oracle 9i DB.

    Here is the code that doesn't work. It works only with baninst1, no other username will work and all I do is change the my_username/my_password to something different. This is one example function where I try to do an insert, but it doesn't work on any of the tables I try.
    Thanks for looking.
    class Oracle {
         private $oracleUser = "my_username";
         private $oraclePassword = "my_password";
         private $oracleDB = "MY_DB";
         private $c = null;
         function Connect() {
              if ( !($this->c = ocilogon( $this->oracleUser, $this->oraclePassword, $this->oracleDB ) ) )
                   return false;
              return true;
         function AddNewTest($testName, $course, $section, $term, $maxAttempts, $length, $startDate, $startTime, $endDate, $endTime)
              $result = "";
              if( $this->c == null )
                   $this->Connect();     
              $splitIndex = strpos($course, " ");
              $subjectCode = substr($course, 0, $splitIndex);
              $courseNumber = substr($course, $splitIndex + 1);
              $insertStatment = "insert into szbtestinfo(szbtestinfo_test_name,
                                                                szbtestinfo_course_numb,
                                                           szbtestinfo_section,
                                                                szbtestinfo_max_attempts,
                                                                szbtestinfo_length_minutes,
                                                                szbtestinfo_start,
                                                                szbtestinfo_end,
                                                                szbtestinfo_id,
                                                                szbtestinfo_subj_code,
                                                                szbtestinfo_eff_term)
                                                                values( '" . $testName .
                   "', '" . $courseNumber .
                   "', '" . $section .
                   "', " . $maxAttempts .
                   ", " . $length .
                   ", to_date('" . $startDate . " " . $startTime . "', 'MM/DD/YYYY HH24:MI')" .
                   ", to_date('" . $endDate . " " . $endTime . "', 'MM/DD/YYYY HH24:MI')" .
                   ", szsnexttest.nextval" .
                   ", '" . $subjectCode .
                   "', '" . $term . "')";
              //return $insertStatment;
              $s = OCIParse($this->c, $insertStatment);
              try
                   $result = OCIExecute($s);
              catch(exception $e)
              return $result;
         }

  • Record not inserting into sap table with connector framework ?

    here is the code, but record not being inserting into the table ... but same piece of code working fine while updating ... the record ...
    try {
    interaction = connection.createInteractionEx();
    IInteractionSpec interactionSpec = interaction.getInteractionSpec();
    String functionName = "Z_XYZ";
    interactionSpec.setPropertyValue("Name", functionName);
    String writingTable = "MYTABLE";
    RecordFactory rf = interaction.getRecordFactory();
    MappedRecord importParams = rf.createMappedRecord("input");
    importParams.put("ATTR1", "VALUE1");
    importParams.put("ATTR2", "VALUE2");
    IFunction function = connection.getFunctionsMetaData().getFunction(functionName);
    IStructureFactory sf = interaction.retrieveStructureFactory();
    IRecordSet table = (IRecordSet) sf.getStructure(function.getParameter(writingTable).getStructure());
    table.insertRow();
    table.setString("ATNAME", "VALUE");
    table.setString("ATWRT", "VALUE");
    importParams.put(writingTable, table);
    MappedRecord output = (MappedRecord) interaction.execute(interactionSpec, importParams);
    } catch (Exception e) {
    any idea?
    than ks
    MMK

    Hi Mohan,
    Does a creation through SE37 with the same input work?
    Yoav.

Maybe you are looking for

  • Recording with a Toshiba DR430TU

    I recently purchased the Toshiba DR430TU at Best Buy and I am having some difficutly in recording programs.  I can watch store bought DVD's, but when I try to record, either by pressing the record button or setting up the timer feature, I only get a

  • Lost keyboard letter

    Where can I get a replacement for a lost letter from my keyboard? We were cleaning it and one of my students lost the W, a pretty important letter! Thanks in advance

  • Invalid directory structure

    Hi +"CANON" has invalid directory structure ..+ I'm working on FCP 6.0 and I get that message during Log and Transfer. The CANON directory is on the camera CANON HF100. I have two iMac 5.1 with FCP 6.0 on the other iMac there is no problem. Plug in t

  • WFM_Op does not return when iterating indefinite​ly?

    I'm using the WFM_Op function with a DAQPad 6020E with the WFMsingleBufRegenerate.C that is provided with NI-DAQ. If I change the number of iterations to zero (i.e., indefinite iterations), it never proceeds to the next instruction. I'd ideally like

  • FMS(Interactive) - Adobe Media Player Tracking Service.

    Hi Folks... I understand that the Flash Interactiver Server has this feature called 'Adobe Media Player Tracking Service' which the free version dosen't have. Any idea what ' Adobe Media Player Tracking Service' is and what it does ? regards