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

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;

Related

Sybase - How To Output Variable Contents To File

I'm writing a procedure in Sybase using Interactive SQL. The proc contains several SELECT statements that store the results in variables, eg
DROP VARIABLE IF EXISTS #totalRows;
CREATE VARIABLE #totalRows LONG VARCHAR;
SELECT COUNT(*) INTO #totalRows FROM <MyTable>;
I'd like to be able to output the results of this query to a CSV file but I get an error when trying to run the following statement
DROP VARIABLE IF EXISTS #totalRows;
CREATE VARIABLE #totalRows LONG VARCHAR;
SELECT COUNT(*) INTO #totalRows FROM <MyTable>;
OUTPUT TO 'C:\\temp\\TEST.CSV' FORMAT ASCII DELIMITED BY ';' QUOTE '' WITH COLUMN NAMES;
The error reads
Could not execute statement.
Syntax error near 'OUTPUT' on line 4.
SQLCODE=-131, ODBC 3 State="42000".
Line 1, column 1
If I remove the OUTPUT TO section of the query it runs fine. Is it possible in Sybase to write the contents of a variable to an external file in this manner?
Seems like, 'OUTPUT' clause is not supported by Sybase.
As a workaround, you may run this query using some text-based tool (like sqlite) and redirect (>) the output into file, if you happen to use linux box at your client end.
Or, you may add ODBC data source (which will require sybase ODBC-driver) corresponding to your DB in Windows and use MS Excel embedded tool Microsoft Query (Data -> From other sources -> From Microsoft Query) in order to export your query result directly into excel datasheet, which you may save as CSV.
OUTPUT TO is a dbisql command, i.e. a directive for the dbisql client utility. It is not a SQL statement. If you try to execute this with anything other than dbisql, you'll get an error.
BTW -- I believe the OUTPUT clause must follow the semicolon that terminates the SELECT stmt, i.e. not have a line break in between.
Need add select variable before output statement
DROP VARIABLE IF EXISTS #totalRows;
CREATE VARIABLE #totalRows LONG VARCHAR;
SELECT COUNT(*) INTO #totalRows FROM <MyTable>;
SELECT #totalRows; --select variable before output
OUTPUT TO 'C:\\temp\\TEST.CSV' FORMAT ASCII DELIMITED BY ';' QUOTE '' WITH COLUMN NAMES;

How to execute sql query when debugging a stored procedure

I'm debugging a stored procedure on SQL Server 2008 and I have this:
INSERT INTO #tempTable (ID, Name)
SELECT ID, Name FROM dbo.MYTABLE WHERE dbo.MYTABLE.Old >= 15
How can I view the data into #tempTable on Debug time?
In SQL Server Management Studio, you can't execute query directly while debugging stored procedure, and that's still not implemented(I think). You can only view the local variables value in Local Debug Window.
There are some work around to see temp table values while in Debugging mode:-
1) In the stored procedure, after insert data into #temptable, add this line of code to get temptable values in xml table varriable where you want to see temptable values. Then you can check the values in Local Debug window in xml format
--inserting data into temp table
INSERT INTO #tempTable (ID, Name)
SELECT ID, Name FROM dbo.MYTABLE WHERE dbo.MYTABLE.Old >= 15
--to see records of temp table
DECLARE #temptable XML
SET #temptable = (SELECT * FROM ##temptable FOR XML AUTO)
2) You can convert local temp table(#temptable) to global temptable(##temptable), so when you insert date in temp table, you can open new query window, and able to see global temp table records using select query.
This blog post describes how to access a temporary table from another session:
http://web.archive.org/web/20180409190701/http://sqlblog.com:80/blogs/paul_white/archive/2010/08/14/viewing-another-session-s-temporary-table.aspx
Alternative you can use two ## in the table name to make the table globally accessible from other sessions: ##tempTable (The table might be locked for reading while your insert is running)
Even though SQL Server Management Studio has some debugging functions , but I find them pretty useless.
I don't think there are any debugging tools out there for SQL Server like Visual Studio, which will give you a step by step information at runtime.
The way normally developers debug sql server code is to use print statement, for stored procedures take the sp definition out declare a variable for each parameter that procedure expects , hardcode the values for variables and execute smaller logical blocks of code to see what's going on where.

Executing dynamically created SQL Query and storing the Query results as a temporary table

I am creating a SQL Query dynamically. After it's been created I want to execute it and store it as a temporary table.
WITH [VALIDACCOUNTS] AS( EXEC (#sqlQuery))
You have two solutions for this:
As a first solution you can simply use an INSERT EXEC. This will work if you have a specified result set. This could be used if your procedure just returns one result set with a fixed result design.
Simply create your temporary table with matching columns and datatypes. After that you can call this:
INSERT INTO #yourTemporaryTable
EXEC(#sql)
The second solution would be the usage of OPENROWSET for this, which may have some sideeffects.
You can read more about it here.
INSERT INTO #yourTemptable
SELECT *
FROM OPENROWSET('SQLNCLI', 'DRIVER={SQL Server};',
'EXEC (''+#sql+''))'

Insert rows from a table in another database

How can rows be inserted into a table from a table in a remote database?
We currently have a stored procedure which does this using a database link. However, we are having to delete the link because our company policy doesn't allow their usage.
begin
...
execute immediate 'insert into '|| table_name
|| ' (select * from schema_name.'|| table_name ||'#link)';
...
end;
I'm unable to use the COPY command as it appears to be not recognized.
COPY FROM username/pwd#SID
insert into table_name using (select *
from table_name);
Error report:
SQL Error: ORA-00926: missing VALUES keyword
00926. 00000 - "missing VALUES keyword"
*Cause:
*Action:
According to this SQL Plus page, COPY command is now obsolete.
Your Query syntax is slightly wrong, and you just need to specify INSERT/REPLACE/CREATE .. and INTO is NOT needed.
COPY is not obsolete, but it ends up with some encoding issues.
You would use the line continuation character to get around that.
COPY
FROM username/pwd#SID
TO username/pass#SID2
insert
table_name
using
select * from schema_name.table_name;
You can also, download the table data into a text file, and use SQL*Loader to load the data into the another Database.
I prefer the SQL*Loader option! Since maintenance is easy!
For download,
- you can either use SPOOL with delimiter option as mentioned Here
- Write a ProC/PLSQL to output the data into a File (Method 4 in ProC, OR select column names from dba_columns))

Debug SQL in pgAdmin when SQL contains variables

In SQL Server I could copy sql code out of an application and paste it into SSMS, declare & assign vars that exist in the sql and run. yay great debugging scenario.
E.g. (please note I am rusty and syntax may be incorrect):
declare #x as varchar(10)
set #x = 'abc'
select * from sometable where somefield = #x
I want to do something similar with Postgres in pgAdmin (or another postgres tool, any recommendations?) where I can just drop my SQL (params & all) into something that will run against Postgres DB.
I realise you can create pgscript, but it doesn't appear to be very good, for example, if I do the equivalent of above, it doesn't put the single quotes around the value in #x, nor does it let me by doubling them up and you don't get a table out after - only text...
Currently I have a piece of SQL someone has written that has 3 unique variables in it which are used around 6 times each...
So the question is how do other people debug SQL efficiently, preferably in a similar fashion to my SQL Server days.
You can achieve this using the PREPARE, EXECUTE, DEALLOCATE commands for handling statements, which is really what we are talking about here.
For example:
PREPARE test AS SELECT * FROM users WHERE first_name = $1;
EXECUTE test ('paul');
DEALLOCATE test;
Perhaps not as graphical as some may like, but certainly workable.
I would give a shot at writing a SQL function that wraps your query. It can be something as simple as
CREATE OR REPLACE FUNCTION my_function(integer, integer)
RETURNS integer
AS
$$
SELECT $1 + $2;
$$
LANGUAGE SQL;
SELECT my_function(1, 2);
I would do this instead of a PREPARE since it will be simpler to update it. Depending on how complex the function is, you might want to also look at some of the other PL's in Postgres.
SQL procs are notoriously hard to debug. My lame but practical solution has been to write log messages to a log table, like this (please excuse syntax issues):
create table log_message (
log_timestamp timestamp not null default current_timestamp,
message varchar(1000)
);
then add lines to your stored proc like:
insert into log_message (message) values ("The value of x is " || #x);
Then after a run:
select * from log_message order by 1;
It's not pretty, but works in every DB.