Insert rows from a table in another database - sql

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))

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;

SQL SERVER: I would like to transfer my data to another column of the same table before droping the first one

I am having problems with some of my SQL scripts on SQL SERVER, indeed I am trying to transfer data from a column A to a column B of the same table and then drop the column B,
However my problem is that I have to check for the existence of A beforehand because the code is meant to be executed on a server where I don't have access (I work as a third party developper on a professionnal app)
Here is my code:
-- Export the data from the column name
-- Drop the column name
USE p_mynacellelocation_db_ChecklistWPF
GO
IF COL_LENGTH('model_trolley_part','name') IS NOT NULL
BEGIN
UPDATE model_trolley_part
SET name_en=[name];
ALTER TABLE model_trolley_part
DROP COLUMN [name];
END
In the case of the column name being non existent I would like not to do anything
However on execution of the code in a database where the column name is non existent SQL Server returns me:
Msg 207, Level 16, State 1, Line 12 Invalid column name 'name'.
Instead of jumping through all these hoops simply rename your original column.
https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql?view=sql-server-2017
exec sp_rename 'model_trolley_part.name', 'name_en', 'COLUMN'
You need to use dynamic SQL for this. The reason is that the parser will try to validate your code, even the code that won't be executed because its IF condition wouldn't be met.
The parser is smart enough to see there is no table named name, but it's not smart enough to realize that the code shouldn't get executed because of the IF, so it raises a parsing error.
Using dynamic SQL in the BEGIN..END block after the IF hides this from the parser so it will execute.
Try this:
IF EXISTS(SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'myTableName'
AND COLUMN_NAME = 'ColumnA')
BEGIN
// your update and drop code goes here
END
you might want to check your account privileges if you are modifying table structure etc..

can we Execute any sql query in sql loader control file

Can we execute any SQL statement using sql control file.
the pseudocode is like
LOAD DATA
INFILE *
DELETE *from STUDENT WHERE STATUS="PASS_OUT"**
APPEND
INTO TABLE STUDENT WHEN (1:1)= '1'
FIELDS TERMINATED BY '|'
.......................
..........................
ERROR
SQL*Loader-350: Syntax error at line X.
Expecting ".......", found keyword delete.
DELETE * from STUDENT where STATUS='PASS_OUT'
^
NOTE:-where "......." is different keywords based on their places.
No, you would have to create a wrapper script around your SQL*Loader call that does that first and on success runs sqlldr.

'Execute Immediate' with Into Clause in HANA

I have a requirement where-in I need to read a table (table name provided as input parameter of the SP), store the results in a temp table and then store the count of the read table into a variable. Please advise how can this be achieved. I have been able to read the table and its count using dynamic query but am not able to put the results in a temp table/ variable. 'Select' and 'Into' clauses do not seem to be working with 'Execute Immediate'. Thanks.
It is not very clear to me exactly what is being asked, but you should be able to execute a SELECT statement in the following manner:
CREATE PROCEDURE p1(IN tablename VARCHAR) AS
BEGIN
execute immediate 'SELECT * FROM ' || :tablename;
END;
Then the following statements create a table and call the procedure to retrieve the result:
create table T (i integer);
insert into T values (123);
The following would produce a result set with one row/column with the value 123:
CALL p1('T')
Please note that with this type of functionality, you need to be very careful not to allow any user-provided input to be given directly to a procedure that uses EXECUTE IMMEDIATE to avoid the possibility of SQL injection attacks.

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;