spool for insert in sql developer not working - sql

I have below select query for which the result of this query i want to create insert scripts and saved it in files. I have used spool.
set long 10000
set lines 100000
set sqlformat insert
spool c:\temp\Insert_TEST_GRP.sql
select ID,NAME,TEST_DATE from TEST_GRP sd
where TEST_DATE =
( select min(TEST_DATE)
from TEST_GRP sd2
where sd.ID = sd2.ID
)
and sd.TEST_DATE <> TO_DATE ('01.01.2000', 'dd.mm.yyyy');
spool off
The file has been created. But when i view the file i am getting the result which is not in the form of insert statements as i want to run this insert statement again.
Below hows the data looks like in file which looks in incorrect format:

We don't have access to your table or your data.
But here it is working with the demo schema HR and its EMPLOYEES table
set sqlformat insert
spool c:\users\jdsmith\desktop\SO_inserts.sql
select * from employees;
spool off
You're using SET LONG - does your table have LOBS in it?
Also, I noticed you asked this same question on the OTN Forums...

The set sqlformat method to format your query results was added in version 4.1.
If you're on an earlier version (e.g. 3.0 as you said in a comment) then it would complain, which you seem to have overlooked; e.g. in 4.0:
set sqlformat insert
gets this in the script output window:
line 1: SQLPLUS Command Skipped: set sqlformat insert
The /*insert*/ method was available earlier than that:
select /*insert*/ * from dual;
which gets
REM INSERTING into dual
SET DEFINE OFF;
Insert into "dual" (DUMMY) values ('X');
(don't really attempt to insert into dual, of course). You can also use the export wizard (tools->database export); or run your query with control-enter, right-click on the output grid and choose 'export' (though it may repeat the query).
Upgrading to the current version is the sensible thing to do though.

You need to return a string that is the INSERT statement formatted with the columns you need. Example
set long 10000
set lines 100000
set sqlformat insert
spool c:\temp\Insert_TEST_GRP.sql
select 'INSERT INTO TEST_GRP (ID,NAME,TEST_DATE) VALUES (' ||
ID||','||NAME||',' || TEST_DATE||');'
from TEST_GRP sd
where TEST_DATE =
( select min(TEST_DATE)
from TEST_GRP sd2
where sd.ID = sd2.ID
)
and sd.TEST_DATE <> TO_DATE ('01.01.2000', 'dd.mm.yyyy');
spool off
If you are using sqldeveloper, then you can just use the built-in export function and export the result grid as inserts.

I used SQL Developer. Make sure to click Run script(F5) instead of run statement.
For multi statement in sample file use "/" between statement.
SET FEEDBACK OFF
set sqlformat insert
spool C:\Necessary_file\Reqular_task\QDE\profile_const.sql
select * from export_profile where profile_name='SPS_DIAG';
/
select * from profile_const where profile_name='SPS_DIAG';
/
select * from profile_panel where profile_name='SPS_DIAG' order by 5
/
spool off

Related

How do I fix the formatting in my spooled csv file in sql*plus

I am using the following script to spool output of a sql query to a csv file. The query extracts data from a view. My sql*plus version is 12.1.0.2.0
set colsep ,
set headsep off
set pagesize 0
set trimspool on
set NULL ' '
spool myfile.csv
select * from my_view;
spool off
The table has few columns with null values and I am required to produce the output like below.
12345,,,ABC,01-JAN-2020
But my actual output looks like this.
12345
A B C ,01-JAN-2020
Why all these whitespaces are coming even between the column data? For null values, there are new lines inserted and commas are missing.
How do I fix this?
I modified the select * statement as following to get the desired output.
select ColA||','||ColB||','||ColC||','||ColD||','||ColE from my_view;
Still out of curiosity, I'd like to know if there's any other way of achieving the same.
Also using the above query messes up the header.

Exporting sql request to csv instead of table data

I need to export data from my Oracle table to a csv file.
Below is the code that I am running under SQL Developer :
set termout off
set serveroutput off
set feedback off
set colsep ';'
set lines 100000
set pagesize 0
set echo off
set feedback off
spool D:\myfile.csv
select *
from Employee;
spool off
However the output of the above code in the csv file is :
select *
from Employee;
I want the data of the Employee table to be in the csv, not the sql statement.
Any idea what might be wrong in the above code? Thanks.
save your sql in a file emp.sql in a directory D:\scripts and use like below;
set term off
set feed off
spool D:\myfile.csv
#D:\scripts\emp.sql
spool off
You're in SQL Developer, so you don't have to write so much code.
SET SQLFORMAT csv
SPOOL C:\your_file.csv
select * from whatever;
spool off
Run with F5

How do I spool to a CSV file using SQL Developer?

i have this kind of script that i want to spool the final output to a csv file. can you please help?
with first_sub as
select etc
,
second_sub as
select etc
select first_column from first_sub* first_column from second_sub etc.
......................................
..basically, i have 2 or more sub queries that i do maths on in my 'final query'
what i need is to be able to spool the output as a csv.
sorry but im not able to post any specific code
ok, to clarify, i CAN ALREADY spool a 'Simple' query
i.e `select *from employees'
what i have is like this
with sub_1 as
select * from employees
,
sub_2 as
select * from other_employees
select something from sub1 * something_else from sub_2
The last bit is what i want to take out to a .csv file please
-- SQL developer
You can use /*csv*/ hint in SQL developer. As #Aleksej suggested, you can see the linked thread for further options.
select /*csv*/ * from employees;
--SQL Plus
set feedback off
set heading on
set underline off
set colsep ','
spool 'mytab.csv'
select * from tab;
spool off

export oracle table in a csv file [duplicate]

This question already has answers here:
How do I spool to a CSV formatted file using SQLPLUS?
(16 answers)
Closed 5 years ago.
I am writting an sql script to export the content of tables in csv files (one table per file). I managed to write a successful script, thanks to the spool function like this :
spool export.csv append
select 'fielda;fieldb;...' from dual
select fielda,fieldb,.... from table
spool off.
The first problem with this, is that I have to do a select from dual to get only the fields name on the first line.
The second problem with this, is that I have to write each field, and it becomes very painfull when you have 10 tables each having more than 20 fields. So my question was, is there any pl sql function, that takes in parameter only the table name, and export the full content in a csv file.
Thanks in advance.
Below might work for you
set termout off
set serveroutput off
set feedback off
set colsep ';'
set lines 100000
set pagesize 0
set echo off
set feedback off
spool on
spool D:\csv_generator_tmp.sql
select qr from
(select 'select '||a.column_name||'||'';''||' qr,a.COLUMN_ID
from user_tab_cols a
where a.table_name = upper('cust')
and a.column_id=1
union
select b.column_name||'||'';''||',b.COLUMN_ID
from user_tab_cols b
where b.table_name = upper('cust') and b.column_id<>1
and b.column_id<>(select max(c.column_id) from user_tab_cols c)
union
select d.column_name||' from cust;',d.COLUMN_ID
from user_tab_cols d
where d.table_name = upper('cust')
and d.column_id=(select max(d.column_id) from user_tab_cols d))
order by column_id asc;
spool off;
spool on
spool D:\cust.csv
#D:\csv_generator_tmp.sql
spool off;
/
No but you can use user_tables and user_tab_cols to select the columns for tables of interest:
select utc.table_name, utc.column_name
from user_tab_cols utc
where utc.table_name = 'CIRCUIT'
You could manage this through a cursor and generate your select columns. You can then execute this query.
Its better to go with UTL_FILE. I would refer to user the Ask tom link https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::p11_question_id:88212348059
with that you can create the file regularly by calling the function.
You can use Python and cx_Oracle module to extract data to disk in CSV format.
Here’s how you connect to Oracle using cx_Oracle:
constr='scott/tiger#localhost:1521/ORCL12'
con = cx_Oracle.connect(constr)
cur = con.cursor()
After data fetch you can loop through Python list and save data in CSV format.
for i, chunk in enumerate(chunks(cur)):
f_out.write('\n'.join([column_delimiter.join(row[0]) for row in chunk]))
f_out.write('\n')
I used this approach when I wrote TableHunter-For-Oracle

Is there an Oracle SQL tool that builds insert statements from a result set?

Is there an Oracle SQL tool that builds insert statements from a result set? We are currently only allowed to use a tool called SQL Station. I'd like to either suggest a tool, like Rapid SQL or CrazySQuirrell, or build my own re-usable chunk of sql.
Where is this result set coming from? If you mean that you want to execute a SELECT, then insert the resulting data into another table, you can do that in a single SQL statement:
INSERT INTO table2 (columnA, columnB)
SELECT columnA, columnB
FROM table1;
PL/SQL Developer will do this as well. I've used both PL/SQL Developer as well as Oracle's SQL Developer, and in my opinion PL/SQL Developer has a smoother and more consistent interface. Not sure about SQL Developer, but PL/SQL Dev. also lets you export result sets as CSV,XML, and HTML.
It also behaves OK under WINE if you're running Linux.
If you want command line tools, the free cx_OracleTools will do this, and some other nice things as well.
http://cx-oracletools.sourceforge.net/
CompileSource - execute statements in a file, checking for errors
CopyData - copy data from one table or view to another
DbDebugger - allows simple debugging of PL/SQL
DescribeObject - describe objects as SQL statements for recreation
DescribeSchema - describe multiple objects as SQL statements for recreation
DumpCSV - dump the results of a select statement as comma separated values
DumpData - dump the results of a select statement as insert statements
ExportColumn - dump the data from a column into a file
ExportData - dump the data from a database into a portable dump file
ExportObjects - describe object as SQL statements for recreation in files
ExportXML - export data from a table into a simple XML file
GeneratePatch - generate SQL script to go from one set of objects to another
GenerateView - generate a view statement for a table
ImportColumn - import the contents of a file into a column in the database
ImportData - import the data dumped with ExportData
ImportXML - import data from an XML file (such as those created by ExportXML)
RebuildTable - generate SQL script to rebuild the table
RecompileSource - recompile all invalid objects in the database
Yes look at Oracle sql developer.Its free can be downloaded from otn.oracle.com
I found this solution, which is what I'm using now. Thanks for all of the help.
It turns out we can use SQL+ too. For some reason I can't run it in SQL Station.
COPY FROM userid/password#from_DB TO userid/password>#to_DB INSERT toDB_tablename USING SELECT * FROM fromDB_tablename where ....;
commit;
In a pinch, using string contatenation works great for smaller statements you want to build:
Select
'Insert Into MyOtherTableTable Values(''' || MyMainTableColumn1 || ''' and ''' || MyMainTableColumn2 || ''')'
From MyMainTable
Right click on the result set of the query, you will get a pop up. select export data and insert. it will ask you for the location to save the file in which insert statements are generated. give file name and the path to save it.
I know it is too late but It could be helpfull for somebody.
If you go to the table, you can "export" the data. The second step is "Specify Data" where you can add some filters.
This only works for a table data.
Cheers
With Oracle SQL-Developer type and execute as script (F5):
select /*insert*/
* from dual;
output:
Insert into "dual" (DUMMY) values ('X');
you can try also /*csv*/" or /*html*/
source: http://www.thatjeffsmith.com/archive/2012/05/formatting-query-results-to-csv-in-oracle-sql-developer/
SELECT /*csv*/ * FROM scott.emp;
SELECT /*xml*/ * FROM scott.emp;
SELECT /*html*/ * FROM scott.emp;
SELECT /*delimited*/ * FROM scott.emp;
SELECT /*insert*/ * FROM scott.emp;
SELECT /*loader*/ * FROM scott.emp;
SELECT /*fixed*/ * FROM scott.emp;
SELECT /*text*/ * FROM scott.emp;