Help with inserting records conditionally in another table
I need some help on this task please. I have a table with some records like so
Table1
Column1 Column2 Column3 Colum4
1 Name1 Lastname1 1,2
2 Name2 Lastname2 3
3 Name3 Lastname3 NULL
4 Name4 Lastname4 1,3
So the last column, Column4 has the number of the column that the values got changed. So the values on the first row on the Columns 1 and 2 got changed. So I have to insert those values in another table and the same for the other records.
Table2
Column1 Column2 Column3
1 Name1 NULL
2 NULL Lastname2
4 NULL Lastname4
Any ideas on how to accomplish this? Any ideas would be much appreciated.
Hi
Try below, Next time please POST DDL & DML
select 1 Column1, 'Name1' Column2, 'Lastname1'Column3, '1,2' Colum4 into #temp union all
select 2 , 'Name2', 'Lastname2', '3' union all
select 3 , 'Name3' , 'Lastname3', NULL union all
select 4, 'Name4', 'Lastname4', '1,3'union all
select 5, 'Name4', 'Lastname4', '1'
select 1 Column1 ,'Name1' Column2, NULL Column3 into #temp1 union all
select 2 ,NULL ,'Lastname2' union all
select 4, NULL, 'Lastname4'
select Column1, Column2, Column3, Colum4 ,C2,C1 from #temp a
--(select Column1, Column2, Column3, case when Colum4 like '%,%' OR Colum4 IS null then Colum4 else Colum4+',' end as Colum4 from #temp) a
outer apply (select COALESCE(Column2,Column3) From #temp1 where column1 = parsename(replace(a.colum4,',','.'),1)) a1(C1)
outer apply (select COALESCE(Column2,Column3) From #temp1 where column1 = parsename(replace(a.colum4,',','.'),2)) a2(C2)
You can also use split function
http://sqlperformance.com/2012/07/t-sql-queries/split-strings
select a.*,COALESCE(a2.Column2,a2.Column3) From #temp a
cross apply dbo.Split(Colum4,',') a1
left outer join #temp1 a2 on a1.item=a2.Column1
Thanks
Saravana Kumar C
Similar Messages
-
Inserting one table records to the another table
Hi There
Though i don't close the Result set , My program throws the following Exception
java.sql.SQLException: ResultSet is ClosedBecause of this my program Inserts only one record in the another table
My code is this
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.DefaultComboBoxModel.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
public class SearchBook extends JDialog implements ActionListener
private JComboBox comboCategory,comboAuthor;
private JSplitPane splitpane;
private JTable table;
private JToolBar toolBar;
private JButton btnclose, btncancel;
private JPanel panel1,panel2,panel3,panel4;
private JLabel lblCategory,lblAuthor;
private Container c;
//DefaultTableModel model;
Statement st;
ResultSet rs;
Vector v = new Vector();
public SearchBook (Connection con)
// Property for JDialog
setTitle("Search Books");
setLocation(40,110);
setModal(true);
setSize(750,450);
// Creating ToolBar Button
btnclose = new JButton(new ImageIcon("Images/export.gif"));
btnclose.addActionListener(this);
// Creating Tool Bar
toolBar = new JToolBar();
toolBar.add(btnclose);
try
st=con.createStatement();
rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
while(rs.next())
v.add(rs.getString(1));
catch(SQLException ex)
System.out.println("Error");
panel1= new JPanel();
panel1.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
lblCategory = new JLabel("Category:");
lblCategory.setHorizontalAlignment (JTextField.CENTER);
c.gridx=2;
c.gridy=2;
panel1.add(lblCategory,c);
comboCategory = new JComboBox(v);
comboCategory.addActionListener(this);
c.ipadx=20;
c.gridx=3;
c.gridwidth=1;
c.gridy=2;
panel1.add(comboCategory,c);
lblAuthor = new JLabel("Author/Publisher:");
c.gridwidth=2;
c.gridx=1;
c.gridy=4;
panel1.add(lblAuthor,c);
lblAuthor.setHorizontalAlignment (JTextField.LEFT);
comboAuthor = new JComboBox();
comboAuthor.addActionListener(this);
c.insets= new Insets(20,0,0,0);
c.ipadx=20;
c.gridx=3;
c.gridy=4;
panel1.add(comboAuthor,c);
comboAuthor.setBounds (125, 165, 175, 25);
table = new JTable();
JScrollPane scrollpane = new JScrollPane(table);
//panel2 = new JPanel();
//panel2.add(scrollpane);
splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
splitpane.setDividerSize(15);
splitpane.setDividerLocation(190);
getContentPane().add(toolBar,BorderLayout.NORTH);
getContentPane().add(splitpane);
public void actionPerformed(ActionEvent ae)
Object obj= ae.getSource();
if(obj==comboCategory)
String selecteditem = (String)comboCategory.getSelectedItem();
displayAuthor(selecteditem);
System.out.println("Selected Item"+selecteditem);
else if(obj==btnclose)
dispose();
else if(obj==comboAuthor)
String selecteditem1 = (String)comboAuthor.getSelectedItem();
displayavailablity(selecteditem1);
//System.out.println("Selected Item"+selecteditem1);
System.out.println("Selected Author"+selecteditem1);
private void displayAuthor(String selecteditem)
try
{ Vector data = new Vector();
rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
System.out.println("Executing");
while(rs.next())
data.add(rs.getString(1));
//((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
comboAuthor.setModel(new DefaultComboBoxModel(data));
//rs.close();
catch(SQLException ex)
System.out.println("ERROR");
private void displayavailablity(String selecteditem1)
try
Vector columnNames = new Vector();
Vector data1 = new Vector();
String bname,bauthor,bcategory,bref1,bavail,bid;
int bref,mid,num;
rs = st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");
while(rs.next())
bname = rs.getString("BName");
bauthor = rs.getString("BAuthorandPublisher");
bcategory = rs.getString("BCat");
bref = rs.getInt("BRef");
if(bref==1)bref1="Yes";
else bref1 = "No";
mid = rs.getInt("Mid");
if(mid==0)bavail="Available";
else bavail="Issued To:"+mid;
bid = rs.getString("BId");
System.out.println("Book Name is::"+bname);
System.out.println("Book Availabilty::"+bavail);
num = st.executeUpdate("insert into BSearch Values('"+bid+"','"+bname+"','"+bcategory+"','"+bauthor+"','"+bavail+"','"+bref1+",')");
System.out.println("Inseted in the table");
/**ResultSetMetaData md= rs.getMetaData();
int columns =md.getColumnCount();
String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
for(int i=1; i<= booktblheading.length;i++)
columnNames.addElement(booktblheading[i-1]);
while(rs.next())
Vector row = new Vector(columns);
for(int i=1;i<=columns;i++)
row.addElement(rs.getObject(i));
data1.addElement(row);
//System.out.println("data is:"+data);
((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
//DefaultTableModel model = new DefaultTableModel(data1,columnNames);
//table.setModel(model);
//rs.close();
//st.close(); */
catch(SQLException ex)
ex.printStackTrace();
}Please help me Friends. I am very new to java. otherwise give me some suggestion to implement this idea in effective manner.
Thank you for your service
CheersHi
Here i am Posting My programs code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.DefaultComboBoxModel.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.*;
public class SearchBook extends JDialog implements ActionListener
private JComboBox comboCategory,comboAuthor;
private JSplitPane splitpane;
private JTable table;
private JToolBar toolBar;
private JButton btnclose, btncancel;
private JPanel panel1,panel2,panel3,panel4;
private JLabel lblCategory,lblAuthor;
private Container c;
//DefaultTableModel model;
Statement st,st1;
ResultSet rs,rs1,rs2;
Vector v = new Vector();
public SearchBook (Connection con)
// Property for JDialog
setTitle("Search Books");
setLocation(40,110);
setModal(true);
setSize(750,450);
// Creating ToolBar Button
btnclose = new JButton(new ImageIcon("Images/export.gif"));
btnclose.addActionListener(this);
// Creating Tool Bar
toolBar = new JToolBar();
toolBar.add(btnclose);
try
st=con.createStatement();
rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
while(rs.next())
v.add(rs.getString(1));
catch(SQLException ex)
System.out.println("Error");
panel1= new JPanel();
panel1.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
lblCategory = new JLabel("Category:");
lblCategory.setHorizontalAlignment (JTextField.CENTER);
c.gridx=2;
c.gridy=2;
panel1.add(lblCategory,c);
comboCategory = new JComboBox(v);
comboCategory.addActionListener(this);
c.ipadx=20;
c.gridx=3;
c.gridwidth=1;
c.gridy=2;
panel1.add(comboCategory,c);
lblAuthor = new JLabel("Author/Publisher:");
c.gridwidth=2;
c.gridx=1;
c.gridy=4;
panel1.add(lblAuthor,c);
lblAuthor.setHorizontalAlignment (JTextField.LEFT);
comboAuthor = new JComboBox();
comboAuthor.addActionListener(this);
c.insets= new Insets(20,0,0,0);
c.ipadx=20;
c.gridx=3;
c.gridy=4;
panel1.add(comboAuthor,c);
comboAuthor.setBounds (125, 165, 175, 25);
table = new JTable();
JScrollPane scrollpane = new JScrollPane(table);
//panel2 = new JPanel();
//panel2.add(scrollpane);
splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
splitpane.setDividerSize(15);
splitpane.setDividerLocation(190);
getContentPane().add(toolBar,BorderLayout.NORTH);
getContentPane().add(splitpane);
public void actionPerformed(ActionEvent ae)
Object obj= ae.getSource();
if(obj==comboCategory)
String selecteditem = (String)comboCategory.getSelectedItem();
displayAuthor(selecteditem);
System.out.println("Selected Item"+selecteditem);
else if(obj==btnclose)
dispose();
else if(obj==comboAuthor)
String selecteditem1 = (String)comboAuthor.getSelectedItem();
displayavailablity(selecteditem1);
//System.out.println("Selected Item"+selecteditem1);
System.out.println("Selected Author"+selecteditem1);
private void displayAuthor(String selecteditem)
try
{ Vector data = new Vector();
rs1= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
System.out.println("Executing");
while(rs1.next())
data.add(rs1.getString(1));
//((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
comboAuthor.setModel(new DefaultComboBoxModel(data));
catch(SQLException ex)
System.out.println("ERROR");
private void displayavailablity(String selecteditem1)
try
Vector columnNames = new Vector();
Vector data1 = new Vector();
String bname,bauthor,bcategory,bref1,bavail,bid;
int bref,mid,num;
//rs2.Open();
rs = st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");
boolean tr=true;
while(rs.next())
if(true)
bname = rs.getString("BName");
bauthor = rs.getString("BAuthorandPublisher");
bcategory = rs.getString("BCat");
bref = rs.getInt("BRef");
if(bref==1)bref1="Yes";
else bref1 = "No";
mid = rs.getInt("Mid");
if(mid==0)bavail="Available";
else bavail="Issued To:"+mid;
bid = rs.getString("BId");
System.out.println("Book Name is::"+bname);
System.out.println("Book Availabilty::"+bavail);
num = st1.executeUpdate("insert into BSearch Values('"+bid+"','"+bname+"','"+bcategory+"','"+bauthor+"','"+bavail+"','"+bref1+",')");
System.out.println("Inseted in the table");
catch(SQLException ex)
ex.printStackTrace();
}Thank you for your service -
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 . -
@Inserting Records in an Internal Table
Hi,
How can I Insert records in an internal table..such that i can insert the records somewhere in the middle based on the entry in a field?INSERT wa INTO TABLE itab INDEX idx .
Effect
This variant can only be used for standard tables and sorted tables. Each line line_spec to be inserted into the line before the table index idx and the table index of the following lines is increased by one. A data object of the type i is expected for idx.
If idx contains a value equal to the number of the existing table lines plus one, the new line is appended as the last line in the internal table. If idx contains a greater value, no line is inserted and sy-subrc is set to 4.
An exception that cannot be handled is raised when:
idx contains a value less than or equal to 0
A line to be inserted would cause a duplicate entry in tables with a unique table key
A line to be inserted would disrupt the sort order of sorted tables
Within a LOOP loop, you can omit the addition INDEX. Each line to be inserted is inserted before the current table line of the LOOP loop. However, if the current line is deleted in the same loop pass, the response is undefined. -
Help with listing records from two tables
Hi: I have two tables joined by the first field. The field is primary key in first table. Need help listing records from both tables with each record one line/record.
create table EVENTS (
event_key varchar2(64) primary key,
event_description varchar2(64),
create_time int
create table EVENT_UPDATES (
event_key varchar2(64) NOT NULL ,
update_description varchar2(64),
update_time int
insert into EVENTS values('Event1', 'This is event1', 1);
insert into EVENT_UPDATES values('Event1', 'Ticket created', 3);
insert into EVENT_UPDATES values('Event1', 'Event cleared', 10);
insert into EVENTS values('Event2', 'This is event2', 4);
insert into EVENT_UPDATES values('Event2', 'Ticket created', 6);
insert into EVENT_UPDATES values('Event2', 'Event cleared', 8);I want to print each record in EVENTS table as one line and corresponding records in EVENT_UPDATES as one line/record like this
Event1 1 This is event1
3 Ticket created
10 Event cleared
Event2 4 This is event2
6 Ticket created
8 Event clearedTIA
Raviselect case weight
when 1 then event_key
end key,
time_val,
description
from (
select event_key,
create_time time_val,
event_description description,
1 weight
from events
union all
select event_key,
update_time,
update_description,
2 weight
from event_updates
order by event_key,
weight
KEY TIME_VAL DESCRIPTION
Event1 1 This is event1
3 Ticket created
10 Event cleared
Event2 4 This is event2
6 Ticket created
8 Event cleared
6 rows selected.
SQL> SY. -
Javascript error with insert record. Please help!
I contacted Adobe support today and they said to get on these forums as they cant help with coding errors.
When i try to insert a Record I get the following error:
while executing onLoad in InsertRecord.htm, the following JavaScript error(s) occurred:
At line 665 of file "C:\Program Files\Adobe DreamweaverCS4\Configaration\ServerBehaviours\PHP_MySQL\InsertRecord.js":
name has no properties
Line 655
if (columnName.toUpperCase() == name.toUpperCase())
Im running Win 7 64bit
I contacted Adobe support today and they said to get on these forums as they cant help with coding errors.
I have formatted my Pc and reinstalled and the same error comes up. If I try to edit and existing insert record it works fine, when I create a new page and then try to add a new insert recordset i get this erro again.
i have since reinstalled Windows & 32Bit to see if that helped, nope. I have installed no extensions its a clean install.
Any help after spending a small fortune on this software.I think you are trying to run the program but you don't have the required class POP3Session.class or it's .java file which you can compile.
Another example for pop3 and smtp is on the following link..check if it helps you..
http://www.cs.umu.se/~hed/java/ch11.htm -
FTP adapter Batching is not inserting records in to multiple tables
Hi,
Env : 11.1.1.5
We have a scenario where we are reading file with the FTP adapter. As the file can be huge, we are using batching option with a batch size of 2000 records. The records in the file is in the Order and Lines format. In Bpel i am inserting those records in database. I have one Db adapter having two tables Orders and lines with a 1:M relation.
Now in the positive test case scenario, Bpel is able to read the file , split it in to batches and successfully inserts the records in the tables (Orders and Lines).
Now when i am testing a negative test case, i have violated the Primary key constraint in one of the record. Now ideally the batch which encountered the issue and failed, none of the records should get inserted in the Orders and Lines table, but that is not happening. In our case, no records are getting inserted to the lines table (which is as expected) but few records are getting inserted in to the Order table of the failed batch.
F.Y.I : Number of Records in the batch can be less then Batch Size.
Any clue on this?
Thanks.Hi Jaap,
thanks for your reply...
Sorry for being a little unclear ...
I have followed the instrunctions in the on-line help of OWB , and :
1) have imported four code tables into a source module . The tables are in an Oracle RDBMS 10g .
2)I have created manually a table - using the OWB client tool - which consisted of some of the columns found in the four tables .
3)I have inserted a Join Operator in order to correlate the four table columns with the columns of the target module.
4)I have defined the Join condition of the the four table columns. In my first post , unintenionally I have written that I removed the Join Operator. I meant the Join Condition in order to make sure that the join condition isn't the reason that the records are not inserted....
5)I have validated and generated the mapping without any errors - not even warnings.
6)I have selected Project->Deployment Manager and I selected the OWB_RUN user - which is the Runtime Repository owner.
7)I have selected the objects to deploy - the mapping , the one table I created in the target module. The deployment has succedded , and the table was created but no records are found in it.
Now , is there a possibility that this problem is caused by absence of the privileges to insert the rows...?
How can I check that the source tables are filled on the registered location of your source module?
Another basic question...
I have created a Runtime Repository owner - called owb_run- using the Runtime Repository Assistant . I use this user in order to deploy the mapping and the new table. I want -and it is created- that table in another schema (user his_dw) - even another database in the same server. Should I run the Runtime Repository owner in this schema (his_dw)???
Thanks , again a lot
Simon -
How to insert records dynamically in a table at run time
hi, all
please help me out,
my problum is how can i insert records from on table to another table at run time dynamically. Initally the records are coming from R/3 backend.
regardsHi,
One way is to first create a Value node (NewNode) with structure binding of that of the model node. Then iterate through the model node, create NewNode elements and set the value from model node elements into it.
IPrivate<view>.I<model node> mele;
IPrivate<view>.I<NewNode> nele;
for(int=0;i<wdContext.node<output>().node<record>().size();i++)
mele = wdContext.node<output>().node<record>().get<record>ElementAt(i);
nele = wdContext.node<NewNode>().create<NewNode>Element();
wdContext.node<NewNode>().addElement(nele);
nele.set<attr>(mele.get<attr>());
Second way is to create that NewNode inside the model node and create a supply function.
Regards,
Piyush. -
Need help with inserting 10MB CLOB
Hi,
I have an urgent issue and desperately need some help.
There are several files on a FTP server that I need to insert their contents into a CLOB type column. One of the files has more than 10MB contents. What I've been doing is after connection is made to the FTP server, read in the contents in a file line by line into a String, then execute a SQL INSERT statement to insert a new record into the target table.
+//.... make connection, read in files and parse into a String variable called fileContents+
String psInsert = "Insert into FileTrack (Name, Contents) values";
PreparedStatment ps = conn.prepareStatement(psInsert "(?,?)");+
ps.setString(1, "some name");
ps.setObject(2, fileContents);
ps.executeUpdate();
The above works fine for all other smaller files, except the 10MB one. The error I got was SQLCODE: -302, SQLSTATE: 22001, which is about not enough space issue. So I increased the CLOB column size and made sure it doesn't exceed the initial CLOB size setting and the database has plenty of space for storing this 10MB file. Still, I got the same error.
Then I tried the following:
ps.setObject(2, fileContents, java.sql.Types.CLOB);
Failed with same error...
Then I tried this:
FileInputStream inputStream = new FileInputStream(fileContents);
ps.setAsciiStream(2, inputStream, (int)()fileContents.length()));
Still failed with the same error....
Then I changed to ps.setCharStream()... still failed....
What other options do I have to insert the 10MB contents? Can someone please help?
Thanks heaps in advance!!we're still trying to upload that CLOB. Takes a while over this 2400bps modem ;)
-
Insert missing rows from another table
Hi
I need to insert rows from another table if there is gaps in my transaction table. For each ärendenr there should be 5 Id status rows (1-5). Except for the fact that the inserted rows never should have higher IdStatus number then the highest value from
the transaction for each Ärendenr. See my example below that illustrates my transaction table, Stages master and the desired result.
Is there some t sql code that could handle this problem?
Best regards
Arne
So far i have tried to solve this with the code below but it doesnt work.
I have copied the transaction file information to the TempLogTransTimes
and then insert into LogTransTimes
IF OBJECT_ID('dbo.TempLogTransTimes', 'U') IS NOT NULL --Här raderas den tillfälliga tabellen
DROP TABLE dbo.TempLogTransTimes;
SELECT *
INTO TempLogTransTimes
FROM LogTransTimes
DECLARE @TopÄrende INT
WHILE EXISTS(SELECT * FROM TempLogTransTimes)
BEGIN
SET @TopÄrende = (SELECT TOP(1) Ärendenr FROM TempLogTransTimes ORDER BY Ärendenr)
INSERT INTO LogTransTimes(Ärendenr, IdStatus, StatusNamn, SourceId)
SELECT @TopÄrende, SM.IdStatus, SM.StatusNamn, 'Beräkning'
FROM Statusmall SM
FULL JOIN TempLogTransTimes LT ON SM.IdStatus = LT.IdStatus
WHERE LT.IdStatus IS NULL
DELETE TempLogTransTimes WHERE Ärendenr = @TopÄrende
END
Arne OlssonHi Arne Olsson, try this..
DECLARE @Transactions TABLE
Id1 INT,
IdStatus INT,
StatusName VARCHAR(10)
DECLARE @Stages TABLE
IdStatus INT,
StatusName VARCHAR(10)
INSERT INTO @Transactions VALUES(1,1,'AA'), (1,3,'CC'), (1,5,'EE'), (2,1,'AA'), (2,3,'CC')
INSERT INTO @Stages VALUES (1,'AA'), (2,'BB'), (3,'CC'), (4,'DD'), (5,'EE')
;WITH CTE AS(SELECT DISTINCT Id1 FROM @Transactions)
SELECT Id1, IdStatus, StatusName FROM CTE, @Stages
EXCEPT
SELECT Id1, IdStatus, StatusName FROM @Transactions
Please mark as answer, if this has helped you solve the issue.
Good Luck :) .. visit www.sqlsaga.com for more t-sql code snippets and BI related how to articles. -
Comparing Two tables with 300k records and update one table
Could you let me know how to compare two tables having 300k records and update one table.below is the scenario.
Table Tabl_1 has columns A,B and Tabl_2 has columns B,new_column.
Column B has same data in both the tables.
I need to update Tabl_2 in new_column with Tabl_1 A column data by comparing B column in both tables.
I m trying to do using PLSQL Tables.
Any suggestion?
Thanks.Hi,
Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved, so that the people who want to help you can re-create the problem and test their ideas.
Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
If you're asking about a DML statement, such as UPDATE, the CREATE TABLE and INSERT statements should re-create the tables as they are before the DML, and the results will be the contents of the changed table(s) when everything is finished.
Always say which version of Oracle you're using (for example, 11.2.0.2.0).
See the forum FAQ: https://forums.oracle.com/message/9362002
ef2019c7-080c-4475-9cf4-2cf1b1057a41 wrote:
Could you let me know how to compare two tables having 300k records and update one table.below is the scenario.
Table Tabl_1 has columns A,B and Tabl_2 has columns B,new_column.
Column B has same data in both the tables.
I need to update Tabl_2 in new_column with Tabl_1 A column data by comparing B column in both tables.
I m trying to do using PLSQL Tables.
Any suggestion?
Thanks.
Why are you trying to use PL/SQL tables? If tabl_1 and tabl_2 are regular database tables, it will be much simpler and faster just to use them.
Depending on your requirements, you can do an UPDATE or MERGE, either in SQL or in PL/SQL. -
Need help with INSERT and WITH clause
I wrote sql statement which correctly work, but how i use this statment with INSERT query? NEED HELP. when i wrote insert i see error "ORA 32034: unsupported use of with clause"
with t1 as(
select a.budat,a.monat as period,b.vtweg,
c.gjahr,c.buzei,c.shkzg,c.hkont, c.prctr,
c.wrbtr,
c.matnr,
c.menge,
a.monat,
c.zuonr
from ldw_v1.BKPF a,ldw_v1.vbrk b, ldw_v1.bseg c
where a.AWTYP='VBRK' and a.BLART='RV' and a.BUKRS='8431' and a.awkey=b.vbeln
and a.bukrs=c.bukrs and a.belnr=c.belnr and a.gjahr=c.gjahr and c.koart='D'
and c.ktosl is null and c.gsber='4466' and a.gjahr>='2011' and b.vtweg='01'
,t2 as(
select a.BUKRS,a.BELNR, a.GJAHR,t1.vtweg,t1.budat,t1.monat from t1, ldw_v1.bkpf a
where t1.zuonr=a.xblnr and a.blart='WL' and bukrs='8431'
,tcogs as (
select t2.budat,t2.monat,t2.vtweg, bseg.gjahr,bseg.hkont,bseg.prctr,
sum(bseg.wrbtr) as COGS,bseg.matnr,bseg.kunnr,sum(bseg.menge) as QUANTITY
from t2, ldw_v1.bseg
where t2.bukrs=bseg.bukrs and t2.belnr=bseg.BELNR and t2.gjahr=bseg.gjahr and BSEG.KOART='S'
group by t2.budat,t2.monat,t2.vtweg, bseg.gjahr,bseg.hkont,bseg.prctr,
bseg.matnr,bseg.kunnr
,t3 as
select a.budat,a.monat,b.vtweg,
c.gjahr,c.buzei,c.shkzg,c.hkont, c.prctr,
case when c.shkzg='S' then c.wrbtr*(-1)
else c.wrbtr end as NTS,
c.matnr,c.kunnr,
c.menge*(-1) as Quantity
from ldw_v1.BKPF a,ldw_v1.vbrk b, ldw_v1.bseg c
where a.AWTYP='VBRK' and a.BLART='RV' and a.BUKRS='8431' and a.awkey=b.vbeln
and a.bukrs=c.bukrs and a.belnr=c.belnr and a.gjahr=c.gjahr and c.koart='S'
and c.ktosl is null and c.gsber='4466' and a.gjahr>='2011' and b.vtweg='01'
,trevenue as (
select t3.budat,t3.monat,t3.vtweg, t3.gjahr,t3.hkont,t3.prctr,
sum(t3.NTS) as NTS,t3.matnr,t3.kunnr,sum(t3.QUANTITY) as QUANTITY
from t3
group by t3.budat,t3.monat,t3.vtweg, t3.gjahr,t3.hkont,t3.prctr,t3.matnr,t3.kunnr
select NVL(tr.budat,tc.budat) as budat,
NVL(tr.monat,tc.monat) as monat,
NVL(tr.vtweg,tc.vtweg) as vtweg,
NVL(tr.gjahr, tc.gjahr) as gjahr,
tr.hkont as NTS_hkont,
tc.hkont as COGS_hkont,
NVL(tr.prctr,tc.prctr) as prctr,
NVL(tr.MATNR, tc.MATNR) as matnr,
NVL(tr.kunnr, tc.kunnr) as kunnr,
NVL(tr.Quantity, tc.Quantity) as Quantity,
tr.NTS as NTS,
tc.COGS as COGS
from trevenue TR full outer join tcogs TC
on TR.BUDAT=TC.BUDAT and TR.MONAT=TC.MONAT and TR.GJAHR=TC.GJAHR
and TR.MATNR=TC.MATNR and TR.KUNNR=TC.KUNNR and TR.QUANTITY=TC.QUANTITY
and TR.VTWEG=TC.VTWEG and TR.PRCTR=TC.PRCTR
Edited by: user13566113 on 25.03.2011 5:26Without seeing what you tried it is hard to say what you did wrong, but this is how it would work
SQL> create table t ( n number );
Table created.
SQL> insert into t
2 with test_data as
3 (select 1 x from dual union all
4 select 2 x from dual union all
5 select 3 x from dual union all
6 select 4 x from dual)
7 select x from test_data;
4 rows created.
SQL> -
How to insert records in user defined tables through DI Server API
Hi All,
I have created a UDO using some userdefined tables .I am able to insert records in the user defined tables using DI API but problem is that now I want to insert records in those tables using DI Server API but I dont know how to do that please give me some way to do that
Thanks and Regards
UtpalThe AddObject message is :
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
<env:Header>
<SessionID>...</SessionID>
</env:Header>
<env:Body>
<dis:AddObject xmlns:dis="http://www.sap.com/SBO/DIS">
<BOM>
<BO>
<AdmInfo>
<Object>...</Object>
</AdmInfo>
</BO>
</BOM>
</dis:AddObject>
</env:Body>
</env:Envelope>
How to use it with a user defined table ? -
How to insert record inside the internal table in below code
Hi all,
My requirement is to find the sub-total and need to insert in between the internal table.
You can see the output ....where I want the sub-total F2 when 1 & 2 combindely , 3 , 4& 5 combindely .Please check it and let me know is it possible
when i am using modification it is not creating extra row inside the table instead it is modifying one row and putting the total there.
For ex: the origianl output is
F1 F2 F3
A 1 1
B 1 1
F 2 1
D 3 1
E 4 1
C 5 1
We want to display all the total of f2 of 1-2 , 3 , 4-5
so expcected output is
F1 F2 F3
A 1 1
B 1 1
F 2 1
* 3 ->This is the sub-total of 1& 2 of f2
D 3 1
* 1 ->this is the sub-total of 3
E 4 1
C 5 1
* 2 -> this is the sub-total of 4 & 5
= space
But coming output is
A 1 1
B 1 1
* 3 -> it is modifying the F row and inserting the total .Total is comong correct but is shoule insert instead of modifying the record!!
* 1
E 4 1
* 2
Please help how to insert the row total at the end of the chage of field
Please find the below code ..Due to space problem i am attaching below
SasHere is the solution ....i Got the answer Thanks for your helping hands friends
REPORT YTEST_MODIFY.
DATA: BEGIN OF ITAB OCCURS 1,
TOT TYPE C,
F1 TYPE C,
F2 TYPE C,
F3 TYPE I ,
END OF ITAB.
DATA: BEGIN OF JTAB OCCURS 1,
F1 TYPE C,
F2 TYPE C,
F3 TYPE I ,
END OF JTAB.
START-OF-SELECTION.
ITAB-F1 = 'A'.
ITAB-F2 = 1.
ITAB-F3 = 1.
APPEND ITAB.
ITAB-F1 = 'B'.
ITAB-F2 = 1.
ITAB-F3 = 1.
APPEND ITAB.
ITAB-F1 = 'C'.
ITAB-F2 = 5.
ITAB-F3 = 1.
APPEND ITAB.
ITAB-F1 = 'D'.
ITAB-F2 = 3.
ITAB-F3 = 1.
APPEND ITAB.
ITAB-F1 = 'E'.
ITAB-F2 = 4.
ITAB-F3 = 1.
APPEND ITAB.
ITAB-F1 = 'F'.
ITAB-F2 = 2.
ITAB-F3 = 1.
APPEND ITAB.
SORT ITAB BY F2.
LOOP AT ITAB.
WRITE:/1 ITAB-F1 ,
8 ITAB-F2 ,
10 ITAB-F3 .
ENDLOOP.
LOOP AT ITAB.
IF ITAB-F2 = 1 OR ITAB-F2 = 2.
ITAB-TOT = 1.
MODIFY ITAB.
ELSEIF ITAB-F2 = 3.
ITAB-TOT = 3.
MODIFY ITAB.
ELSEIF ITAB-F2 = 4 OR ITAB-F2 = 5.
ITAB-TOT = 4.
MODIFY ITAB.
ENDIF.
ENDLOOP.
SKIP 2.
SORT ITAB BY TOT.
DATA : L_SUM(2) TYPE C,
L_ROW(2) TYPE C.
LOOP AT ITAB.
MOVE-CORRESPONDING ITAB TO JTAB.
APPEND JTAB.
L_SUM = L_SUM + ITAB-F3 .
AT END OF TOT.
CLEAR JTAB.
JTAB-F3 = L_SUM .
APPEND JTAB.
CLEAR L_SUM.
ENDAT.
ENDLOOP.
LOOP AT JTAB.
WRITE:/1 JTAB-F1 ,
8 JTAB-F2 ,
10 JTAB-F3 .
ENDLOOP.
* DATA: a TYPE i , b .
* LOOP AT itab.
* IF b = 0.
* a = a + itab-f3.
* ENDIF.
* AT END OF tot.
* MOVE space TO itab-f1.
* MOVE space TO itab-f2.
* MOVE a TO itab-f3.
* MODIFY itab .
* CLEAR a.
* b = 1.
* ENDAT.
* b = 0.
* ENDLOOP.
* LOOP AT itab.
* MOVE-CORRESPONDING itab TO jtab.
* APPEND jtab.
* ENDLOOP.
* ULINE.
* LOOP AT jtab.
* WRITE: / jtab-f1 , jtab-f2 , jtab-f3.
* ENDLOOP. -
Insert records into non base table
Hi
I would like to insert records into a table when a button is clicked. The table is a non base table. I am trying to save records displayed in a form into a history table which is not part of the form. I am using the following code stored in a program unit then called when the button is pressed. It doesn't generate any error but the records are not inserted. Can anyone please help.
hist_id := 1;
cust_name := :CUSTOMER.cust_name;
loan_date := :LOAN.loan_date;
return_date := LOAN.return_date;
FORMS_DDL('INSERT INTO LOAN_HISTORY VALUES'||hist_id||','||cust_name||','||loan_date||','||return_date);Why do you need forms_ddl built in for a DML statement to be used in form?
U can directly use insert.
hist_id := 1;
cust_name := :CUSTOMER.cust_name;
loan_date := :LOAN.loan_date;
return_date := LOAN.return_date;
INSERT INTO LOAN_HISTORY VALUES (hist_id,cust_name,loan_date,return_date);
It should work perfectly.
Maybe you are looking for
-
Solution Manager 4.0 Configuration: SLDAPIUSER role
In SPRO, SAP Reference IMG -> SAP Solution Manager -> Basic Settings -> SAP Solution Manager System -> System Landscape -> Automatic System Landscape Data Capture -> Connection of System Landscape Directory to Solution Manager -> Generate authorizati
-
Balance sheet account postings to Internal order
Hi All, I have a situation in which I have to make a prepaid expense from a BS account but want to assign it to an internal order so that when this expense actually occur, I can use this internal order report for all the prepayment made against that
-
Where can I download the SDK for SCSM 2012 RTM (version 7.5.1561.0)? I have an older SCSM 2012 system that I'm not sure what SDK is compatible with it. The reason is that I need to run SMLets on that older version in PowerShell. Thanks!
-
Help to restore my iphone and it will not write error 1002
help to restore my iphone 3gs and it will not write error 1002
-
AIS freezes when trying to create a new metadata catalog
Hi, I'm really new in EIS/AIS. We are using EIS and Essbase version 9.3.1. I just created a new odbc connection to our data warehouse (Oracle in OraHome92). I tried to create a new catalog but EIS freezes. When I tried to "end task" the console, it c