SQL script to generate another [INSERT] SQL script - sql

I have a weird SQL situation in which I need to create a SQL script that I would run against database A and it would output another SQL script that would contain INSERT statements which I can then run against database B and upload the data (essentially an Export from A to B but a longer way).
I was wondering if anyone has worked on this an can suggest a way to generate INSERT statements that would contain data from [Database A].[Table Student] which can then be uploaded to [Database B].[Table Student].
Thanks a lot.

You can concat the values from student into an insert string like:
SELECT concat('Insert INTO Students VALUES(', Col1,', ', '''', Col2, '''', ')')
AS [Details]
FROM Student
WHERE ...
N.B The four single quotes is to create a single quote before and after varchar columns for example.
To generate a new SQL script from this, I'd create a cmd file with something like:
SET SERVER=YOUR_SERVER
SET DATABASE=YOUR_DB
sqlcmd -S %SERVER% -d %DATABASE% -h -1 -i Script.sql -o NewScript.sql -W

-- You Can Simple Use insert into statement
INSERT INTO [Database B].[Table Student]
SELECT * FROM [Database A].[Table Student]
WHERE StudentID NOT IN (SELECT StudentID FROM [Database B].[Table Student])

Here is one way that would insert data from one database table to other database table
INSERT INTO [DestinationDB].[dbo].Student
SELECT * FROM [SourceDB].[dbo].Student
GO

If you have access to the both databases you can do it in one query like this:
INSERT INTO [Database A].[Table Student]
OUTPUT inserted.*
INTO [Database B].[Table Student]
SELECT *
FROM [newdata];

Related

Duplicating a SQLite table, indexes, and data [duplicate]

Is there an easy way to copy an existing table structure to a new one?
(dont need the data, only the structure -> like id INTEGER, name varchar(20) ...)
Thx
You could use a command like this:
CREATE TABLE copied AS SELECT * FROM mytable WHERE 0
but due to SQLite's dynamic typing, most type information would be lost.
If you need just a table that behaves like the original, i.e., has the same number and names of columns, and can store the same values, this is enough.
If you really need the type information exactly like the original, you can read the original SQL CREATE TABLE statement from the sqlite_master table, like this:
SELECT sql FROM sqlite_master WHERE type='table' AND name='mytable'
SQLite cannot clone table with PK, defaults and indices.
Hacking by another tool is necessary.
In shell, replace the table name by sed.
sqlite3 dbfile '.schema oldtable' | sed '1s/oldtable/newtable/' | sqlite3 dbfile
And you can check new table.
sqlite3 dbfile '.schema newtable'
Primary key, defaults and indices will be reserved.
I hope this command can help you.
sqlite> .schema
CREATE TABLE [About](
[id],
[name],
[value]);
.schema command will give you structure of About-table how it could be made by programming SQLite interpreter by hand, typing in commands.
Paste in and execute, the CREATE block giving the table new name:
sqlite> CREATE TABLE [AboutToo](
[id],
[name],
[value]);
.tables command now will show you have two tables, old and new, "copied".
sqlite> .tables
About AboutToo
p.s. sqlite> is command prompt you get in console after launching SQLite.exe interpreter. To get it go to www.sqlite.org
Just for the record - This worked for me:
CREATE TABLE mytable (
contact_id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
phone TEXT NOT NULL UNIQUE
);
-- Two variations
INSERT INTO mytable VALUES ( 1, "Donald", "Duck", "noone#nowhere.com", "1234");
INSERT INTO mytable ( contact_id,first_name,last_name,email,phone ) VALUES ( 2, "Daisy", "Duck", "daisy#nowhere.com", "45678");
.output copied.sql
-- Add new table name
.print CREATE TABLE copied (
-- Comment out first line from SQL
SELECT "-- " || sql FROM sqlite_master WHERE type='table';
.output
.read copied.sql
.schema
select * from copied;
Beware that this only works if schema is wrapped after CREATE TABLE mytable (.
Otherwise you'll need some string replacement using .system
Yes by using the SQLiteStudio you can use the last icon in the structure table called create similar table from any existing table.
I would prefer :
> sqlite3 <db_file>
sqlite3 > .output <output_file>
sqlite3 > .dump <table_name>
The line above generates the dump of table that includes DDL and DML statement.
Make changes in this file, i.e. find and replace the table name with new table name
Also, replace "CREATE TRIGGER " with "CREATE TRIGGER <NEWTABLE>_" , this will replace existing triggers with trigger names with a new table name on it. That will make it unique and will not cause conflicts with existing triggers. Once all schema changes are implemented, read it back into database using .read
sqlite3 > .read output_file
This can be scripted in shell file using shell commands like :
echo ".dump <table>" | sqlite3 <db_file> > <table_file>
sed -i.bak "s/\b<table_name>\b/<new_table_name>/g" <table_file>
sed -i.bak "s/\bCREATE TRIGGER \b/CREATE TRIGGER <new_table_name_>/g" <table_file>
echo ".read <table_file>" | sqlite3 <db_file>
rm <table_name>.bak
For example :
If you have table T and new table is TClone in db file D with file F to be created : then
echo ".dump T" | sqlite3 D.sqlite > F
sed -i.bak "s/\bT\b/TClone/g" F
sed -i.bak "s/\bCREATE TRIGGER \b/CREATE TRIGGER TClone_>/g" F
echo ".read F" | sqlite3 D.sqlite
rm T.bak
Finally, you can generalize this script by creating a parameterized version where you can pass source_table, destination_table , db_file as parameters that can be used to clone any table.
I tested this and it works.
Testing :
sqlite3 <database_file>
sqlite3 > select * from <new_table>;
should give you same results as original table. and
sqlite3 > .schema <new_table>
should have same schema as that of original table with a new name.

How to execute or run .sql file inside stored procedure in oracle

I am trying to create stored procedure to create scheduled task . Which will execute my .sql script daily. My .sql file contains create table and drop table scripts. like this
Drop table a608232_new_62K_master;
create table a608232_new_62K_master as select A.* from
a608232_MRD_DATA_62K_W_Account A inner join a608232_new_mids B
on A.MID = B.MID;
Many more statements like this which updates that table daily. How should I proceed regarding this. I am trying to create procedure so that i can schedule a task to execute that procedure. Or is there some other way to this in oracle.
ps: I have only 1 .sql file which contains all the statements.
I would suggest using Oracle Scheduler to execute your scripts with PL/SQL Packages Procs and use execute immediate when required for DDL.
Hope that works out for you.
Regards,
Ted
You can put the code in your .sql file, inside a stored procedure.
CREATE PROCEDURE myproc
AS
BEGIN
Drop table a608232_new_62K_master;
create table a608232_new_62K_master as select A.* from
a608232_MRD_DATA_62K_W_Account A inner join a608232_new_mids B
on A.MID = B.MID;`
END
Then You can automate this using a batch file and windows task scheduler.
set MYDB= yourDBname
set MYUSER=youruser
set MYPASSWORD=yourpassword
set MYSERVER=yourservername
sqlcmd -S %MYSERVER% -d %MYDB% -U %MYUSER% -P %MYPASSWORD% -h -1 -s "," -W -Q "exec myproc"
Try creating a table like this :
CREATE PROCEDURE myproc
AS
BEGIN
Drop table a608232_new_62K_master;
create table a608232_new_62K_master (col1, col2, col3...) -- Note: Its better to name the columns in the table, same as the columns used by the select query
insert into a608232_new_62K_master (col1, col2, col3...)
select A.col1, A.col2, A.col3 from
a608232_MRD_DATA_62K_W_Account A
inner join a608232_new_mids B
on A.MID = B.MID;`
END

bcp won't output temp tables

I have a stored procedure that stores values in temp tables.
It all works well, but I can not bcp it with
exec master..xp_cmdshell 'bcp "exec sp_test '2006-07-21' " queryout c:\test.txt -c '
If I change the table to regular, then it all works. Can you not use temp tables this way?
I would not necessarily want to share the code as it contains company stuff, but it is basically like this
SELECT
*
INTO #Extractr
FROM
TABLE A
WHERE ID in (4,9,14)
The error message is invalid object #Extractr
Thanks!
I have just stumbled upon this a few days ago.
What I've learned from this link:
http://www.dbforums.com/microsoft-sql-server/1605565-can-we-have-temporary-table-store-procedure-when-using-bcp.html
is that it won't see temp tables as they'd be in the tempdb database not the one you are using.
Also, I got mine working by replacing the local temp tables to global ones (## instead of # with a simple replace helped me).
As #Kevin has mentioned in the comments, you can alternatively use table variables for the same purpose.
Hope this will work for you.
Have you tried referencing the temp table like this in your query: tempdb..#Extractr
For example:
SELECT
*
INTO tempdb..#Extractr
FROM
TABLE A
WHERE ID in (4,9,14)
Using table variables instead of temp tables helped me to figure it out.
DECLARE #tbl1 TABLE
(fld1 int,...)
INSERT INTO #tbl1
SELECT * FROM Table1

How to include SQL code in SQL query?

Prior to my main select statement, I first have to create a temporary table with thousands of lines (using a select statement to get these lines automatically is not feasible in my SQL Server environment), but working in that SQL query is a nightmare of readability, as my .sql file has thousands of lines :(
Is is possible to achieve something like this ?
include('actors_tables.sql') /*including all the insert code*/
select * from #temp_actors
instead of this ?
create table #temp_actors (firstname varchar(50), lastname varchar(50))
insert into #temp_actors values ('George','Clooney')
insert into #temp_actors values ('Bill','Murray')
insert into #temp_actors values ('Bruce','Willis')
... + 1000 inserts in thousands of lines
select * from #temp_actors
Seems to me like a basic simple feature but I can't find how to achieve this ...
The server is running SQL Server 2005, and I'm using SQL Server Management Studio 2008.
Thank you for your help !
Kris.
From the command prompt, start up sqlcmd:
sqlcmd -S <server> -i C:\<your file name here>.sql -o
Or to run from sql server management studio use xp_cmdshell and sqlcmd:
EXEC xp_cmdshell 'sqlcmd -S ' + #DBServerName + ' -d ' + #DBName + ' -i ' + #FilePathName
you can use Sqlcmd in command prompt with input file (use sqlcmd -i actors_tables.sql ).

How can I dump data that I want of some SQLite3 tables in SQL format?

I know how to select which table I want to dump in SQL format with the shell command:
$ ./sqlite3 test.db '.dump mytable' > test.sql
But this command selects all the data of "mytable"
Can I select the data in my table that I want before dump and how?
In other terms I seek a command like :
$ ./sqlite3 test.db '.dump select name from mytable' > test.sql
Obviously this command does not work :'(
The only way to do it within the sqlite console is to create a temporary table:
CREATE TABLE tmp AS SELECT (field1, field2 ... ) FROM yourTable WHERE ... ;
.dump tmp
DROP TABLE tmp