INSERT INTO table. . . SELECT field1, field2 From. . . .bug
Hi,
I should remember this but . . . bug with t-sql using Insert Into on a temp table. It is unhappy with fields I'm trying to insert.
It's probably the fact that I'm trying to using some default data w/ aliases for a couple of the fields.
Have a look at code please, and tell me how to correct. Thanks!
DECLARE @OrderNo varchar(6)
USE tempdb;
set @OrderNo = '909773' ;
IF OBJECT_ID ('#tmpNCGLITEMS') IS NOT NULL --how to get this to work with SSMS w/o reloading the qry window. i.e. how to release to delete????
DROP TABLE #tmpNCGLItems
use DEV_ORDERS;
SELECT distinct od.lline as OrdLine, od.ldrcolor as ClrCode, od.ldrspec as SpecCode, ad.Addon_Mod_GL_Acct as ncGLCode
INTO #tmpNCGLItems
FROM OODETL od
INNER JOIN [Dev_Products].[dbo].[Addon_Master] ad on od.lfg = ad.Addon_Mod_Mod_Code_ID AND ad.Addon_Mod_A_C_D_ID = 'C'
WHERE od.LOrder = @OrderNo and ad.Addon_Mod_GL_Acct is not null
select * from #tmpNCGLItems
USE tempdb;
IF OBJECT_ID ('#tmpNCGLITEMS1') IS NOT NULL
DROP TABLE #tmpNCGLItems1
USE DEV_ORDERS;
CREATE TABLE [dbo].[#tmpNCGLItems1](
[OrdLine] [char](4) NOT NULL,
[ClrCode] [char](6) NULL,
[SpecCode] [varchar](6) NULL,
[ClrUPorDiscAmt] money NULL, [SpecUPorDiscAmt] money NULL,
[ncGLCode] [varchar](10) NULL, [lPrice] money Null
) ON [PRIMARY]
--insert into below is failing. Says fields don't match----Msg 213, Level 16, State 1, Line 33
--Insert Error: Column name or number of supplied values does not match table definition.
--but. . . I think I have 7 fields and I think the datatypes match?
INSERT INTO #tmpNCGLItems1
SELECT ordLine, ClrCode, SpecCode, 0 as [ClrUPorDiscAmt], 0 as [SpecUPorDiscAmt], ncGLCode,
SUM(od.lextendprice) as lPrice
FROM #tmpNCGLItems tmp JOIN OODETL od on tmp.OrdLine = od.lline
WHERE od.lorder = @OrderNo
GROUP BY ordLine, ClrCode, SpecCode, NcGLCode
>> I should remember this but . . . bug with T-SQL using Insert Into on a temp table. It is unhappy with fields [sic] I'm trying to insert. It's probably the fact that I'm trying to using some default data w/ aliases for a couple
of the fields [sic: columns are not fields]. <<
Temp tables are how a bad programmer fakes a scratch tape so his SQL can look like magnetic tape files. We do not like to materialize data on the disk unless we have to.
And data element do not change names from table to table in a schema! Get rid of the aliases, even tho they are closer to ISO-11179 than the base table crap.
But you are an old FORTRAN programmer! Your "OODETL” is six uppercase letters as required by FORTRAN I; an SQL programmer would have used something like “Order_Details” instead. The mix of camelCase, FORTRAN and several other non-SQL languages is scary.
Why did you use MONEY? It is not portable and the math is wrong. Google it! Why do you think that “<something>_code_id” makes any sense? A data element can be a “<something>_code” or a “<something>_id” but never that hybrid disaster.
I would do this with VIEWs so that I know the data is always current.
CREATE VIEW NC_GL_Items (..)
AS
SELECT DISTINCT OD.l_line, OD.ldr_color, OD.ldr_spec,
AD.addon_mod_gl_acct
FROM Oodetl AS OD,
Addon_Master AS AD
WHERE ..;
The SELECT DISTINCT should not be there. An account should not be NULL, etc. Why do you have more nulls in one table than entire accounting systems? Why do you set integer zero to an amount, which should be a decimal for money?
This is a crazy quilt that is clearly a bitch to maintain or even read. Can you clean it up or are you screwed?
--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
Similar Messages
-
below i post my code :
import java.util.*;
import java.sql.*;
import java.io.*;
import com.hxtt.sql.*;
public class backofficeDbfVerification {
public backofficeDbfVerification(String path) throws SQLException {
Properties prop = new Properties();
prop.setProperty("user", "");
prop.setProperty("OtherExtensions","true");
prop.setProperty("Version Number", "03");
try {
Class.forName("com.hxtt.sql.dbf.DBFDriver").newInstance();
connection = DriverManager.getConnection("jdbc:DBF:/"+path, prop);
catch (ClassNotFoundException classnotfoundexception) {
System.out.println("could ot find HXTT class, make sure the classpath have been defined in your system !");
catch(Exception e) {
System.out.println(e.getMessage());
public void createBadRecord(String table, String newtable, int blth) throws SQLException {
Statement stmt = connection.createStatement();
String insert = "insert into \""+newtable+"\" select * from \""+table+"\"";
boolean bInsert = stmt.execute(insert);
stmt.close();
public static void main (String args[]) {
String path = "C:\\MASTER\\SOURCEDATA\\AREA";
try {
backofficeDbfVerification test = new backofficeDbfVerification(path);
test.createBadRecord("source\\area\\123.AA2","source\\area\\others\\89964568.AA1");
catch(SQLException sqx) {
System.out.println("Error "+sqx.getMessage());
i try to perform simple query : insert into tablea select from tableb which has same structure. the source table has only 9 rows, but the process ran very long time, no error message raised,it just run and never end (which make me upset for the whole day).
i have tried another simple query : insert into table1 values (1,2) using the same driver and execute successfully.
is it becoz of function limitation since i used evaluation copy ?Copy the answer from HXTT's support forum:
No function limitation. I just tested:
create table testa1 select * from test;
insert into testa1 select * from test;
Passed.
I also run your backofficeDbfVerification.java sample. Passed too. I'm using the same code as you. The difference is only my 89964568.AA1 and 123.AA2 is simulative tables files. If possible, please zip your 89964568.AA1 and 123.AA2 and email to [email protected] Thanks.
BTW, I pasted the little modified backofficeDbfVerification.java below:
import java.sql.*;
import java.util.*;
public class backofficeDbfVerification {
Connection connection;
public backofficeDbfVerification(String path) throws SQLException {
Properties prop = new Properties();
prop.setProperty("user", "");
prop.setProperty("OtherExtensions", "true");
prop.setProperty("Version Number", "03");
try {
Class.forName("com.hxtt.sql.dbf.DBFDriver").newInstance();
connection = DriverManager.getConnection("jdbc:DBF:/" + path, prop);
catch (ClassNotFoundException classnotfoundexception) {
System.out.println("could ot find HXTT class, make sure the classpath have been defined in your system !");
catch (Exception e) {
System.out.println(e.getMessage());
public void createBadRecord(String table, String newtable) throws
SQLException {
Statement stmt = connection.createStatement();
String insert = "insert into \"" + newtable + "\" select * from \"" +
table + "\"";
boolean bInsert = stmt.execute(insert);
stmt.close();
public static void main(String args[]) {
String path = "f:\\dbffiles";
try {
backofficeDbfVerification test = new backofficeDbfVerification(path);
test.createBadRecord("source\\area\\123.AA2",
"source\\area\\others\\89964568.AA1");
catch (SQLException sqx) {
System.out.println("Error " + sqx.getMessage());
} -
How insert into table select from table works in jdbc driver?
Hi, Supposing one table has two LOB fields, one LOB field is BLOB type while the other is CLOB type, I use the following sql statement to copy a row into a new row:
insert into table (id, file_body, file_content) select new_id, file_body, file_content from table where id = '111';
After commit on the connection, I can see the copied record in the table and both LOB fields are not null and this's the expected behavior.
However after some days later, the copy function becomes to be a problem, the BLOB field named file_body can be null when the copy job is done, while other fields copy successfully.
The issue can not be reproduced every time.
I suppose the jdbc driver may try to allocate byte buffer in the heap to perform copy operation for BLOB fields,if there is no enough memory available in the heap the copy operation may fail but the commit on the connection can be successful.b/c I can see a lot of OOM errors in the log files and I believe this can contribute to the issue.
Hope someone can give me a hint or comments.
Thanks,
SuoNayiI want to figure out what's memory leak point and I have tried the following solutions but none worked:
1.I have tried to dump the memory of the JVM but failed,I can see the following errors :
[root@localhost xxx]# jmap -heap:format=b 3027
Attaching to process ID 3027, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 1.5.0_16-b02
Unknown oop at 0x00002b21a24cd550
Oop's klass is null
Finding object size using Printezis bits and skipping over...
Unknown oop at 0x00002b21a3634380
Oop's klass is null
Finding object size using Printezis bits and skipping over...
2.and the thread stack can not be dumped successfully as well:
Thread 3046: (state = BLOCKED)
- java.lang.Object.wait(long) @bci=0 (Compiled frame; information may be imprecise)
Error occurred during stack walking:
the version of java is:
java version "1.5.0_16"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_16-b02)
Java HotSpot(TM) 64-Bit Server VM (build 1.5.0_16-b02, mixed mode)
I have to added dump thread stack option in JVM arguments, -XX:+HeapDumpOnOutOfMemoryError.
If there are other solutions please let me know, thanks. -
System getting hanged whilst using Insert into table select * from table
I have a peculiar problem.
I am using the below statements:
Query 1:
insert into table ppms.erin_out@ppms_dblink select * from erin_out;
Query 2:
insert into table ppms.erin_out@ppms_dblink values(23,'dffgg',12',dfdfdgg,dfdfdg);
I am in 'interfaces' schema (testing server) and executing above statements. We have testing server and development server, both are identical, i.e one is clone of the other.
ppms_dblink is created in interfaces schema. ppms_dblink points to different database server which has two schemas 'clarity' and 'ppms'. ppms_dblink is create through authentication details of clarity schema.
erin_out table is created on ppms schema on the same dababase server pointed by ppms_dblink.
Question is :
TOAD hangs while running query 1.
Query 2 is working perfectly.
As I have pl/sql script which is using query 1. I want to know why query 1 is creating problem.
If I use query 2 in my pl/sql query then it may create performance issue as i have to use cursor then.
On clarity schema, I have insert, update, select, modify rights on ppms.erin_out.
I have tried same queries from another database server.
That is I tried queries from 'interfaces' schema of development server ( clone of the testing server ). Its working perfectly.
Message was edited by:
user484158Dhanchik:
The table from which I select rows, to insert into table on dblink, is having only one record. It may contatin maximum 100 rows at a time because I am scheduling the procedure through daemon process. Anyway transaction is not more than 100 records. I am trying with just 1 record for testing.
So 1) Problem is not about the cost, TOAD is getting hanged ( to insert 1 record, cost does not mean much)
2) there is no large amount of data, so no question of deteriorated performance
Aron Tunzi:
I think that should not be problem, because I am able to insert a record through query 2.
Warren Tolentino :
I am testing with 1 record only. Its not performance issue.
Message was edited by:
रचित -
INSERT INTO TABLE (SELECT -----)
I laready posted But i think people got confused this is the same query in easiest way
Hi Please please here Insdie the curusr FOR Loop i am using INSERT INTO by SELECT (see the below code EACH INSERT WILL FETCH 800-1000 records Minimum !!!)
In that satement here i am using the MINUS also ,,thi is taking minute to insert each record approx
This way I need to insert 5 insert Into sattement for different tables see EXA
Inside the FOR loop------
INSERT INTO PICKSLIP
( SELECT FIELDS
FROM table p, table d
WHERE ---- AND ---
AND ---
AND -----
IN ( SELECT Fields
FROM p, d
WHERE ---- AND ---
AND ----
MINUS
SELECT PICKSLIP_PREFIX, PICKSLIP_NUMBER FROM C
GROUP BY Fields);
This WAY
5 insert it dam slow taking 1 minutes to insert to all 5 tables ...this way i have lot of recordss....But i think people got confused this is the same query in easiest way I don't think this is more clear with your current thread. Your query is bad, and shouldn't work at all.
It shouldn't work for too many reasons (at least because AND without nothing behind) and use a group by clause where is not required.
Nicolas. -
Ain't getting it: insert into table by determing value from another table
I have a table (PERCENTILE_CHART) with percentiles and test scores for different tests:
Structure:
Percentile, Reading_Test, Writing_Test
Data:
30,400,520
31,450,560
97,630,750
98,630,780
99,640,800
The data is currently in ascending order by Percentile.
If a person took the Reading test and scored 630 he or she would be in the 98th (not 97th) percentile of the class taking that test.
I wrote a statement to return the percentile:
select Percentile
from ( select ROWNUM, PERCENTILE
from PERCENTILE_CHART
where READING_TEST <= '650'
order by READING_TEST desc)
where ROWNUM < 2 order by PERCENTILE desc;
This select works and is able to determine the highest percentile for a score.
Ok, now I want to process all the records in a STUDENT table which have
test scores and insert them in a new table along with the percents, normalizing the data in the process.
Have this:
STUDENT:
Student_Name,Student_ID,
John Smith,121,Reading,98,Writing,90
Maggie Smithe,122,Reading,95,Writing,96
And needs to be moved to into SCORES with the percentiles, so I get this:
SCORES:
Student_Name,Student_ID,Test_Name,Percentile
121,Reading,98
121,Writing,90
122,Reading,95
122,Writing,96
This is were I get confused. How do I insert the data into the SCORES table with the percentile? I think calling a function in package is the way to do it:
function oua_Test_Percentile_f (
p_Test_Name in char,
p_Test_Value in char)
return char as
-- Declare variables
c_Return_PTile char(2);
begin
select PERCENTILE into c_Return_PTile
from (select ROWNUM, PERCENTILE
from PERCENTILE_CHART
where p_Test_Name <= '&p_Value'
order by p_Test_Nmae desc)
where ROWNUM < 2 order by PERCENTILE desc;
return c_Return_PTile;
end;
But this function doesn't return the percentile even though it is based on my working select mentioned earlier. It returns a blank for all tests.
And even if it is working how do I then populate the SCORES table?You may want to use analytical functions so that you can determine the percentile across all of the different scores:
SQL> with
2 PERCENTILE_CHART as
3 (
4 select 30 PERCENTILE, 400 READING_TEST, 520 WRITING_TEST from dual union all
5 select 31 PERCENTILE, 450 READING_TEST, 560 WRITING_TEST from dual union all
6 select 97 PERCENTILE, 630 READING_TEST, 750 WRITING_TEST from dual union all
7 select 98 PERCENTILE, 630 READING_TEST, 780 WRITING_TEST from dual union all
8 select 99 PERCENTILE, 640 READING_TEST, 800 WRITING_TEST from dual
9 )
10 select
11 max(percentile) over (partition by reading_test) HIGHEST_READING,
12 max(percentile) over (partition by writing_test) HIGHEST_WRITING,
13 percentile_chart.*
14 from
15 percentile_chart
16 /
HIGHEST_READING HIGHEST_WRITING PERCENTILE READING_TEST WRITING_TEST
30 30 30 400 520
31 31 31 450 560
98 97 97 630 750
98 98 98 630 780
99 99 99 640 800
SQL>
I wasn't exactly sure how you wantd to coorelate this to the student records though; the student table had only two column name headings but there were four rows listed as examples and had fewer rows than in the percentile_chart table...
If you join the student table to the able query it might be what you are looking for.
You can create another table based on the output of your query by doing:
create table scores
as select * from
(insert your query here)
/ -
I have a script task written in C# that creates an array of strings "arrayFields" after parsing a text file. It saves the array of strings in a DTS variable.
Each row in array represents a row is comma separated and is a row that must be inserted into a table. For example,
X and Z are fields in the table
X1, X2,....Xn
Z1,Z2,...Zn
I am using a Foreach Loop to grab each row and then Execute SQL Task to take each row from the array and insert each field per row in a table,
The SQL is something like,
INSERT dbo.table values(field1, field2,...fieldn) arrayFields?
What should this this INSERT look like?I guess you implemented
Shredding a Recordset
Based on what I understood (correct me if I am wrong) you have difficulties mapping the input parameters, if so here is the guide
http://www.sqlis.com/sqlis/post/The-Execute-SQL-Task.aspx
In short it might look like
INSERT dbo.table (ColumnA, ColumnB,...) VALUES (?,?...)
The syntax for the T-SQL INSERT is http://technet.microsoft.com/en-us/library/dd776381%28v=sql.105%29.aspx
Arthur
MyBlog
Twitter -
Insert into table values from 2 different tables
Hi ,
i have 2 tables as below ,
table A
ELITE FREQ_ITEM COMBINED_STR SUP
;1;10;2;3;4;5;7;8 ;10;2;3;4;5;8;9 ;1;2;3;4;5;7;8;9;10 1
;10;2;3;4;5;8;9 ;10;2;3;4;5;8;9 ;2;3;4;5;8;9;10 2table B
FREQ_ITEM SUB ITEM_LEN
;1;10;2;3;4;5;7;8 2 8
;10;2;3;4;5;8;9 2 7
;10;2;3;4;5;8;9;1 1 8i want to insert values in Table C as below ,
insert into table C "ELITE","SUP" from Table A when "SUP" in table A >=2
Else Select "FREQ_ITEM","SUB" from Table B when "A"."ELITE"="B"."FREQ_ITEM"
The result should be like below ,
ELITE SUP
;10;2;3;4;5;8;9 2
;2;3;4;5;8;9;10 2any help please .
Edited by: 876602 on 09/10/2011 04:24 صIt is not clear what are you trying to do. Based on expected results, something like:
select case
when sup < 2 then elite
else combined_str
end elite,
sub
from tableA a,
tableB b
where a.elite = b.freq_item
ELITE SUB
;1;10;2;3;4;5;7;8 2
;2;3;4;5;8;9;10 2
SQL> SY. -
Use of sequence numbers while inserting into tables
Hi,
Consider i have a stored procedure where i insert records into 30 to 40 tables.
for example i have a table A and a sequence SEQ_A for that table.
Is there any difference in performance in the following two ways of
insertion,
1. select SEQ_A.NEXTVAL into variable_a FROM DUAL;
INSERT INTO A VALUES(variable_a);
2.INSERT INTO A VALUES (SEQ_A.NEXTVAL).
I have 30 to 40 insert statements like that in method 1.
if i replace it by method 2. will there be any improvement in performance?
Thanks & Regards
SundarThis could be interesting. I agree that triggers should be used for data integrity, though even better is to only allow write access to tables via stored procedures.
Anyway while you are waiting for the test case that shows triggers are faster, which could take some time, it is quick and easy to come up with a test case that shows the opposite.
SQL> create table t (id number, dummy varchar2(1));
Table created.
real: 40
SQL> insert into t select s.nextval, 'a' from all_objects;
29625 rows created.
real: 5038
SQL> rollback;
Rollback complete.
real: 40
SQL> create trigger tt before insert on t
2 for each row
3 begin
4 select s.nextval into :new.id from dual;
5 end;
6 /
Trigger created.
real: 291
SQL> insert into t select null, 'a' from all_objects;
29626 rows created.
real: 13350
SQL> rollback;
Rollback complete.
real: 1082
SQL>Note with triggers even the rollback took longer.
Martin -
Insert into table a (select * from table b) - need pk?
Hi there.
I'm going to insert into table FINAL (select * from table STAGING) - same structure but in STAGING the ID column has nulls.
Do I need to provide the ID (primary key) for table FINAL or will it get created based on sequence/trigger?
If I were doing this in a loop I'd get the next val from the sequence but on a simple insert, I'm curious.
thanks!hmm.. what is ?
it didn't like it.
Error(11,4): PLS-00103: Encountered the symbol "[" when expecting one of the following: begin case declare exit for goto if loop mod null pragma raise return select update while with <an identifier> <a double-quoted delimited-identifier> <a bind variable> << close current delete fetch lock insert open rollback savepoint set sql execute commit forall merge <a single-quoted SQL string> pipe
9i, sqldeveloper -
Using combination of insert into and select to create a new record in the table
Hello:
I'm trying to write a stored procedure that receives a record locator parameter
and then uses this parameter to locate the record and then copy this record
into the table with a few columns changed.
I'll use a sample to clarify my question a bit further
-- Create New Amendment
function create_amendment(p_mipr_number in mipr.mipr_number%TYPE, p_new_amendment_number in mipr.amendment_number%TYPE)
return integer is
new_mipr_id integer;
begin
THIS is causing me grief See comments after this block of code
insert into mipr
(select mipr_id from mipr where mipr_number=p_mipr_number),
(select fsc from mipr where mipr_number=p_mipr_number),
45,
(select price from mipr where mipr_number=p_mipr_number),
practical,
(select part_number from mipr where mipr_number=p_mipr_number);
THe above will work if I say the following
insert into mipr
(select * from mipr where mipr_number=p_mipr_number);
BUt, Of course this isn't what I want to do... I want to duplicate a record and change about 3 or 4 fields .
How do I use a combination of more than one select and hard coded values to insert a new record into the table.
/** Ignore below this is fine... I just put a snippet of a function in here ** The above insert statement is what I need help with
select (mipr_id) into new_mipr_id from mipr where mipr_number=p_mipr_number + amendment_number=(select max(amendment_number) + 1);
return new_mipr_id;
end;
THANK YOU IN ADVANCE!
KTfunction create_amendment(p_mipr_number in mipr.mipr_number%TYPE)
return integer is
new_mipr_id integer;
tmp_number number;
tmp_mipr_id integer;
begin
tmp_number :=(select max(amendment_number) from mipr where mipr_number=p_mipr_number);
Question:
tmp_number :=1; works..
tmp_number doesn't work with the select statement?
Obviously I'm a novice! I can't find anything in my book regarding tmp variables... What should I look under is tmp_number a
variable or what? In my Oracle book, variable means something different.
Thanks!
KT
I have the following code in my stored procedure:
Good luck,
Eric Kamradt -
Insert into table a large amount of records
I was trying to find a fast way to optimize a script that insert a large amount of records into a table. The initial script was like
insert into table_xxxx
select a.camp1, a.camp2, a.camp3 a.camp4, b.camp1, b.camp2, b.camp3
from table_a a, table_b b
where a.camp0 = b.camp0
The commit sentence was at the end of the insert script; so i came up with this solution
Declare
TYPE cur_CURSOR IS REF CURSOR ;
TYPE Tab_Hist IS TABLE OF table_xxxx%ROWTYPE INDEX BY BINARY_INTEGER;
g_tHist Tab_Hist;
CURSOR c_Base IS
select a.camp1, a.camp2, a.camp3 a.camp4, b.camp1, b.camp2, b.camp3
from table_a a, table_b b
where a.camp0 = b.camp0;
BEGIN
OPEN c_base;
LOOP
FETCH c_base BULK COLLECT INTO g_tHist LIMIT 1000;
EXIT WHEN g_tHist.COUNT = 0;
BEGIN
FORALL i IN g_tHist.FIRST .. g_tHist.COUNT SAVE EXCEPTIONS
INSERT INTO prov_cobr_dud VALUES g_tHist(i);
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
NULL;
END;
g_tHist.DELETE;
EXIT WHEN c_base%NOTFOUND;
END LOOP;
CLOSE c_base;
commit;
END;
If anyone could tell me another way to do the same thing i'll apreciate it a lot; i'm keen on learn more efficient ways to optimize scripts.
PD: The initial insert was inserting the table with 120,000 records (more or less)Hello,
Wrong forum. This is the Oracle Forms forum. You should post in the SQL-PL/SQL forum.
Francois -
How do i insert into table through forms
Hi
I have developed a custom form based on custom table.
the only way to insert data into database table is through form.
there are two tables: one table is to store all contract details & second table is to maintain history forthis.
one condition(col1,col2,col3,col4) are unique combination,we are not creating any PK or FK at database level.evrythng is captured at form level.
if all 4 columns combination exist thn e should not insert that record.
if 4 columns combination doesnot exist then insert into table.
I have used just pre insert,pre update triggers.
I think its a basic form functionality ,by itself it inserts ,update record.now it is doing the same thng.
But I have to add the above condition ,how can i do that.
Pl provide me some ex code .
Thank you.
Hope any one can help meSQL> create table t
2 (object_id number
3 ,object_name varchar2(30));
Table created.
SQL>
SQL> create sequence t_seq;
Sequence created.
SQL>
SQL> insert into t (object_id, object_name)
2 select t_seq.nextval
3 ,object_name
4 from all_objects
5 ;
52637 rows created. -
How to insert into table, of table description of table
Dear All,
I need to take the table description of the table and i need to insert that description in to a new table column , please help me to how to write the query for these.
many thanks in advance
Sreenivasulu Puser627163 wrote:
Dear All,
I need to take the table description of the table and i need to insert that description in to a new table column , please help me to how to write the >query for these.Why insert into a new column into the same table ? That would be madness. :) (kidding)
You can explore with this :
[oracle@g5 ~]$ sqlplus scott/tiger
SQL*Plus: Release 11.1.0.6.0 - Production on Tue Jun 2 09:23:10 2009
Copyright (c) 1982, 2007, Oracle. All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - 64bit Production
With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> create table dtable (tablename varchar2(20),col_name varchar2(20),Not_null varchar2(1), datatype varchar2(20) );
Table created.
SQL> desc dtable
Name Null? Type
TABLENAME VARCHAR2(20)
COL_NAME VARCHAR2(20)
NOT_NULL VARCHAR2(1)
DATATYPE VARCHAR2(20)
SQL> set wrap off
SQL> SELECT column_name "Name", nullable "Null?",
CONCAT (CONCAT (CONCAT (data_type, '('), data_length), ')') "Type"
FROM user_tab_columns
WHERE table_name = 'EMP';
Name N Type
EMPNO N NUMBER(22)
ENAME Y VARCHAR2(10)
JOB Y VARCHAR2(9)
MGR Y NUMBER(22)
HIREDATE Y DATE(7)
SAL Y NUMBER(22)
COMM Y NUMBER(22)
DEPTNO Y NUMBER(22)
8 rows selected.
SQL> INSERT INTO dtable
SELECT 'emp', column_name, nullable,
CONCAT (CONCAT (CONCAT (data_type, '('), data_length), ')') "Type"
FROM user_tab_columns
WHERE table_name = 'EMP';
8 rows created.
SQL> commit;
Commit complete.
SQL> select * from dtable;
TABLENAME COL_NAME N DATATYPE
emp EMPNO N NUMBER(22)
emp ENAME Y VARCHAR2(10)
emp JOB Y VARCHAR2(9)
emp MGR Y NUMBER(22)
emp HIREDATE Y DATE(7)
emp SAL Y NUMBER(22)
emp COMM Y NUMBER(22)
emp DEPTNO Y NUMBER(22)
8 rows selected.
many thanks in advancecheers
Sreenivasulu P -
Reg: read excel column and insert into table.
hi Friends,
i wanted to read the data from Excel and insert into in my oracle tables.
can you provide the link or example script.
how to read the column value from excel and insert into table.
please help.< unnecessary reference to personal blog removed by moderator >
Here are the steps:
1) First create a directory and grant read , write , execute to the user from where you want to access the flat files and load it.
2) Write a generic function to load PIPE delimited flat files:
CREATE OR REPLACE FUNCTION TABLE_LOAD ( p_table in varchar2,
p_dir in varchar2 DEFAULT ‘YOUR_DIRECTORY_NAME’,
P_FILENAME in varchar2,
p_ignore_headerlines IN INTEGER DEFAULT 1,
p_delimiter in varchar2 default ‘|’,
p_optional_enclosed in varchar2 default ‘”‘ )
return number
is
– FUNCTION TABLE_LOAD
– PURPOSE: Load the flat files i.e. only text files to Oracle
– tables.
– This is a generic function which can be used for
– importing any text flat files to oracle database.
– PARAMETERS:
– P_TABLE
– Pass name of the table for which import has to be done.
– P_DIR
– Name of the directory where the file is been placed.
– Note: The grant has to be given for the user to the directory
– before executing the function
– P_FILENAME
– The name of the flat file(a text file)
– P_IGNORE_HEADERLINES
– By default we are passing 1 to skip the first line of the file
– which are headers on the Flat files.
– P_DELIMITER
– Dafault “|” pipe is been passed.
– P_OPTIONAL_ENCLOSED
– Optionally enclosed by ‘ ” ‘ are been ignored.
– AUTHOR:
– Slobaray
l_input utl_file.file_type;
l_theCursor integer default dbms_sql.open_cursor;
l_lastLine varchar2(4000);
l_cnames varchar2(4000);
l_bindvars varchar2(4000);
l_status integer;
l_cnt number default 0;
l_rowCount number default 0;
l_sep char(1) default NULL;
L_ERRMSG varchar2(4000);
V_EOF BOOLEAN := false;
begin
l_cnt := 1;
for TAB_COLUMNS in (
select column_name, data_type from user_tab_columns where table_name=p_table order by column_id
) loop
l_cnames := l_cnames || tab_columns.column_name || ‘,’;
l_bindvars := l_bindvars || case when tab_columns.data_type in (‘DATE’, ‘TIMESTAMP(6)’) then ‘to_date(:b’ || l_cnt || ‘,”YYYY-MM-DD HH24:MI:SS”),’ else ‘:b’|| l_cnt || ‘,’ end;
l_cnt := l_cnt + 1;
end loop;
l_cnames := rtrim(l_cnames,’,');
L_BINDVARS := RTRIM(L_BINDVARS,’,');
L_INPUT := UTL_FILE.FOPEN( P_DIR, P_FILENAME, ‘r’ );
IF p_ignore_headerlines > 0
THEN
BEGIN
FOR i IN 1 .. p_ignore_headerlines
LOOP
UTL_FILE.get_line(l_input, l_lastLine);
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND
THEN
v_eof := TRUE;
end;
END IF;
if not v_eof then
dbms_sql.parse( l_theCursor, ‘insert into ‘ || p_table || ‘(‘ || l_cnames || ‘) values (‘ || l_bindvars || ‘)’, dbms_sql.native );
loop
begin
utl_file.get_line( l_input, l_lastLine );
exception
when NO_DATA_FOUND then
exit;
end;
if length(l_lastLine) > 0 then
for i in 1 .. l_cnt-1
LOOP
dbms_sql.bind_variable( l_theCursor, ‘:b’||i,
ltrim(rtrim(rtrim(
regexp_substr(l_lastLine,’([^|]*)(\||$)’,1,i),p_delimiter),p_optional_enclosed),p_optional_enclosed));
end loop;
begin
l_status := dbms_sql.execute(l_theCursor);
l_rowCount := l_rowCount + 1;
exception
when OTHERS then
L_ERRMSG := SQLERRM;
insert into BADLOG ( TABLE_NAME, ERRM, data, ERROR_DATE )
values ( P_TABLE,l_errmsg, l_lastLine ,systimestamp );
end;
end if;
end loop;
dbms_sql.close_cursor(l_theCursor);
utl_file.fclose( l_input );
commit;
end if;
insert into IMPORT_HIST (FILENAME,TABLE_NAME,NUM_OF_REC,IMPORT_DATE)
values ( P_FILENAME, P_TABLE,l_rowCount,sysdate );
UTL_FILE.FRENAME(
P_DIR,
P_FILENAME,
P_DIR,
REPLACE(P_FILENAME,
‘.txt’,
‘_’ || TO_CHAR(SYSDATE, ‘DD_MON_RRRR_HH24_MI_SS_AM’) || ‘.txt’
commit;
RETURN L_ROWCOUNT;
end TABLE_LOAD;
Note: when you run the function then it will also modify the source flat file with timestamp , so that we can have the track like which file was loaded .
3) Check if the user is having UTL_FILE privileges or not :
SQL> SELECT OWNER,
OBJECT_TYPE
FROM ALL_OBJECTS
WHERE OBJECT_NAME = ‘UTL_FILE’
AND OWNER =<>;
If the user is not having the privileges then grant “UTL_FILE” to user from SYS user:
SQL> GRANT EXECUTE ON UTL_FILE TO <>;
4) In the function I have used two tables like:
import_hist table and badlog table to track the history of the load and another to check the bad log if it occurs while doing the load .
Under the same user create an error log table to log the error out records while doing the import:
SQL> CREATE TABLE badlog
errm VARCHAR2(4000),
data VARCHAR2(4000) ,
error_date TIMESTAMP
Under the same user create Load history table to log the details of the file and tables that are imported with a track of records loaded:
SQL> create table IMPORT_HIST
FILENAME varchar2(200),
TABLE_NAME varchar2(200),
NUM_OF_REC number,
IMPORT_DATE DATE
5) Finally run the PLSQL block and check if it is loading properly or not if not then check the badlog:
Execute the PLSQL block to import the data from the USER:
SQL> declare
P_TABLE varchar2(200):=<>;
P_DIR varchar2(200):=<>;
P_FILENAME VARCHAR2(200):=<>;
v_Return NUMBER;
BEGIN
v_Return := TABLE_LOAD(
P_TABLE => P_TABLE,
P_DIR => P_DIR,
P_FILENAME => P_FILENAME,
P_IGNORE_HEADERLINES => P_IGNORE_HEADERLINES,
P_DELIMITER => P_DELIMITER,
P_OPTIONAL_ENCLOSED => P_OPTIONAL_ENCLOSED
DBMS_OUTPUT.PUT_LINE(‘v_Return = ‘ || v_Return);
end;
6) Once the PLSQL block is been executed then check for any error log table and also the target table if the records are been successfully imported or not.
Maybe you are looking for
-
SSO for Enterprise Portal 6 with different Portal and R/3 userIDs
Hi there, We are using SNC library for SAP GUI logon to R/3 and SPNEGO for Web access to EP. What works for us currently is: SSO from Windows logon to Portal using SPNego (LDAP as our datasource with AD) However once we are inside the portal, the SSO
-
Something's wrong with my headphone jack, it only plays the left side!!
I know it's not my headphones, cause I've tried 4 different ones, one of them new, and it''s always the left side that's the only working side. If I wiggle the headphones in the jack, the right side will cut in and out. This just happened today, I ha
-
How to achieve same functionality for String as java in oracle 10g
Example: In java if I use --------------->>> String.format("%03d", 11) then it will give me result 011 String.format("%03d", 1111) then it will give me result 1111 I need same result in Oracle also for a stored procedure. I have used to_char() and lp
-
I'm a Pro Tools user, who just did an "Archive and Install" installation of 10.5.8 over my 10.4.11 on my 2 Ghz G5, now Pro Tools won't launch. I checked the extensions folder and sure enough, the digidesign extensions were left behind. Can I revert
-
Text format error in ALV report
Hi Experts, I am trying to download the ALV report output in to text format but the system is not downloaded the columns correctly. some of the columns are repeating and the alignment also not correct. Please let me know if anyone have solution for t