How do you copy Sql table from one database to another database with differ field names - sql

I have a database name "EmpOld" with a table name "Employee" and a database name "EmpNew" with a table name "Employee".
The table structures are identical on both database tables except for the names in the table.
Here is a definition of the tables:
Database "EmpOld" table name "Employee" has following field names:
int e_id
char(20) e_fname
char(25) e_lname
Database "EmpNew" table "Employee" has following field names:
int id
char(20) fname
char(25) lname
Notice, the only difference in the tables is the "e_" prefix for field names are removed from the EmpNew Employee table.
How do I move data from EmpOld database to EmpNew database?
Is there a code that maps these field respectively.
Thanks community,
Nick

Well, you could just name them manually:
INSERT dbo.EmpNew(fname, lname) SELECT e_fname, e_lname FROM dbo.EmpOld;
If you want to do this without manually typing out the column names, there is magic in SSMS - just drag the Columns folder from each table into the appropriate spot in your query window (and then manually remove identity columns, timestamp, computed columns etc. if relevant).

There is no automatic way of mapping fields, unless with some code.
This can be done in two ways:
Using the SQL Import & Export Wizard
This is the most easy way to do this and here is an article that gives step by step to do this. The key is to change the mapping between the source and destination fields while importing the data.
Writing an SQL
This method requires both the databases to be accessible. Using a simple insert statement as follows this can be achieved
insert into EmpNew.dbo.Employee(id, fname, lname)
select
e_id, e_fname, e_lname
from
EmpOld.dbo.Employee
If they are on same sql server then the above will work good as is. If they are different sql server you may have to add a link server connection and prefix the table commands with that.

Is there a code that maps these field respectively.
No - you'll need to provide the mapping. If you're using an ETL tool like SSIS there may be a way to programatically map columns based on some criteria, but nothing built into SQL.

Maybe you can generate code with help from the tables sys.columns and other system tables so that you can make the copy-process run automatically.
I think you can't use:
insert into (...) (...)
because you have two databases. So just generate insert statements like:
insert into table (...) VALUES (...)
Please correct me if i misunderstood the question.

There are 2 ways you can do without the data loss.
1) you can use Insert statement
`
Insert into EmpNew (ID,fname,lname)
Select e_id, e_fname, e_lastname
from EmpOld
`
2) You can simple use Import-Export Wizard
Go to Start Menu > SQL Server 2008/2008R2/2012 > ImportandExport>
This will take you the wizard box
Select Source :- DataSource(ServerName) and Database where you are
extracting data from
Select Destination : DataSource(ServerName) and Database where you are extracting data to
Map the table
BE AWARE of PK/FK/Identity
you are good to go

Related

How to make a new copy of table without CREATE TABLE but using INSERT

I'm using SQL Server 2014 and trying to figure out some not trivia task.
I have a table PROPERTY and need to copy some of the data to absolutely new table PROPERTY_1 (PROPERTY_1 is not created and I'm not allowed to use CREATE TABLE). I have to use INSERT only!
I've googled some fancy commands like INSERT INTO from MySQL:
INSERT INTO PROPERTY_1 SELECT * FROM PROPERTY
but it's no help because (surprise-surprise!) PROPERTY_1 is not created.
Is it any possible way to pass this task or it's just some kind of weird task?
You must use Select Into as described in the Microsoft: documentation
You can use Select into to create the structure only and use Insert into to copy the data like below:
SELECT * INTO PROPERTY_1 FROM PROPERTY WHERE 1=0
INSERT INTO PROPERTY_1 SELECT * FROM PROPERTY
Benefits of using Select into to create the structure of the copy table:
You don't need to worry about the columns and their data types in the new table (PROPERTY_1) as those will be similar to the base table (PROPERTY). The new table schema will match the original schema, including identity columns.
There won't be any errors while inserting the records in the new table.

Oracle : 2 column names for a single column

There is a requirement to rename the DB tables and column names,
so all the tools/application taking data from the source will have to change their queries. The solution we are planning to implement is that for every table name change we will create a VIEW with the original table name. Easy and simple to implement. No query change required, but there are cases where a table name remains the same but a column name changes within the table, so we can't create another view (any object with the same object name).
Is there a Column Synonym kind of thing which we can propose here?
Any solutions/ideas are welcome. Requirement is to have queries containing original column names referring to the new columns in the same tables.
For example:
Table Name: DATA_TABLE
Existing Column Name: PM_DATE_TIME
New Column Name: PM_DATETIME
Existing Query select pm_Date_time from Data_Table; should refer to new column pm_Datetime
You could consider renaming your original table, and then create a View in its place providing both the old and the new column-names:
CREATE TABLE Data_Table ( pm_Date_time DATE );
ALTER TABLE Data_Table RENAME TO Data_Table_;
CREATE VIEW Data_Table AS
(
SELECT pm_Date_time,
pm_Date_time AS pm_Datetime -- Alias to provide the new column name
FROM Data_table_
);
-- You can use both the old columnn-name...
INSERT INTO Data_Table( pm_Date_time ) VALUES ( SYSDATE );
-- ... or the new one
UPDATE Data_Table SET pm_Datetime = SYSDATE;
There are things that won't work the same way as before:
-- INSERT without stating column-names will fail.
INSERT INTO Data_Table VALUES ( SYSDATE );
-- SELECT * will return both columns (should not do this anyway)
SELECT * FROM Data_Table
Once you are done with your changes drop the view and rename the table and the columns.
You'll want to add virtual columns:
ALTER TABLE Data_Table ADD pm_Date_time as (pm_Datetime);
UPDATE: Oracle (11g at least) doesn't accept this and raises "ORA-54016: Invalid column expression was specified". Please use Peter Lang's solution, where he pseudo-adds zero days:
ALTER TABLE Data_Table ADD (pm_Datetime + 0) AS pm_Date_time;
This works like a view; when accessing pm_Date_time you are really accessing pm_Datetime.
Rextester demo: http://rextester.com/NPWFEW17776
And Peter is also right in this point that you can use it in queries, but not in INSERT/columns or UPDATE/SET clauses.
This was basically touched on in the answer by Thorsten Kettner, but what your looking for is a pseudocolumn.
This solution looks a little hacky because the syntax for a pseudocolumn requires an expression. The simplest expression I can think of is the case statement below. Let me know if you can make it more simple.
ALTER TABLE <<tablename>> ADD (
<<new_column_name>> AS (
CASE
WHEN 1=1 THEN <<tablename>>.<<old_column_name>>
END)
);
This strategy basically creates a new column on the fly by evaluating the case statement and copying the value of <old_column_name> to <new_column_name>. Because you are dynamically interpolating this column there is a performance penalty vs just selecting the original column.
One gotcha here is that this will only work if you are duplicating a column once. Multiple pseudocolumns cannot contain duplicate expressions in Oracle.
we cant create a another view (any object with the same object name).
That's true within a schema. Another somewhat messy approach is to create a new user/schema with appropriate privileges and create all your views in that, with those querying the modified tables in the original schema. You could include instead-of triggers if you need to do more than query. They would only need the old columns names (as aliases), not the new ones, so inserts that don't specify the columns (which is bad, of course) would still work too.
You could also create synonyms to packages etc. in the original schema if the applications/tools call any and their specifications haven't changed. And if they have changed you can create wrapper packages in your new schema.
Then your legacy tools/applications can connect to that new schema and if it's all set up right will see things apparently as they were before. That could potentially be done by setting current_schema, perhaps through a login trigger, if the way they connect or the account they connect to can't be modified.
As the tools and applications are upgraded to work with the new table/column names they can switch back to the original schema.

How to copy data and structure of table from one table to another?

In my first database named 'sshopping' has two tables IndiaStates and IndiaCity. I want to copy these both table in new database 'jaijinendera' .
IndiaStates has columns StateID (Primary Key) and StateName
IndiaCity has columns CityID(Primary Key) , StateID (Foreign Key),CityName
I used the query something like this
Insert int jaijinendera..IndiaStates select * from sshopping..IndiaStates
Insert int jaijinendera..IndiaCity select * from sshopping..IndiaCity
this has copied the data but not the keys (structure). What query should i made to copy proper structure and data from sshopping to jaijinendera
Try using the SQL Server Generate script.
Right click on DB where you want to export table structure and data. Select Task and generate script.
follow the wizard. Select the object or entire database in the select object you want to generate script. Click on the Advance to select schema only (for structure)/ data only for data and schema and data for both.
generate the script to file or clipboard.

How do I stitch together tables using SQL?

Ok, I am learning SQL and just installed SQL Server. I've read about outer joins and inner joins but am not sure either is what I want. Basically, I want to reconstruct a text file that has been "chopped" up into 5 smaller text files. The columns are the same across all 5 text files, e.g. name, age, telephone #, etc. The only difference is that they have different numbers of rows of data.
What I'd like to do is "append" the data from each file into one "mega-file". Should I create a table containing all of the data, or just create a view? Then, how do I implement this...do I use union? Any guidance would be appreciated, thanks.
Beyond your immediate goal of merging the five files it sounds like you want the data contained in your text files to be generally available for more flexible analysis.
An example of why you might require this is if you need to merge other data with the data in your text files. (If this is not the case then Oded is right on the money, and you should simply use logparser or Visual Log Parser.)
Since your text files all contain the same columns you can insert them into one table*.
Issue a CREATE statement defining your table
Insert data into your newly created table**
Create an index on field(s) which might often be used in query predicates
Write a query or create a view to provide the data you need
*Once you have your data in a table you can think about creating views on the table, but to start you might just run some ad hoc queries.
**Note that it is possible to accomplish Step 2 in other ways. Alternatively you can programmatically construct and issue your INSERT statements.
Examples of each of the above steps are included below, and a tested example can be found at: http://sqlfiddle.com/#!6/432f7/1
-- 1.
CREATE TABLE mytable
(
id int identity primary key,
person_name varchar(200),
age integer,
tel_num varchar(20)
);
-- 2. or look into BULK INSERT option https://stackoverflow.com/q/11016223/42346
INSERT INTO mytable
(person_name, age, tel_num)
VALUES
('Jane Doe', 31, '888-888-8888'),
('John Smith', 24, '888-555-1234');
-- 3.
CREATE UNIQUE INDEX mytable_age_idx ON mytable (age);
-- 4.
SELECT id, person_name, age, tel_num
FROM mytable
WHERE age < 30;
You need to look into using UNION.
SELECT *
FROM TABLE1
UNION
SELECT *
FROM TABLE2
And I would just create a View -- no need to have a stored table especially if the data ever changes.

Create a replica of a sql table

I need a query to create a table which is the exact replica but with different table name and without any data from the source table using a sql query!
You can try this
SELECT * INTO Table_Copy
FROM Table
where 1=2
It will create a empty table with the same structure.
SQL Server Management Studio
Object Explorer
Connect -> Your server
Databases -> Choose Database
Tables
Right Click Your Table
Script Table as -> Create To -> New Query Editor Window
Jonathan has it (upvoted), and you should probably go with that because it's more portable. I normally use something similar:
SELECT TOP 0 * INTO [New_Table] FROM [Old_Table]
I think this better expresses what you're doing, but I like Jonathan's because 'TOP 0' is SQL Server specific, and so his is more portable.
For MySQL, you can call SHOW CREATE TABLE table_name;
It will display a CREATE TABLE query. Simply change the table name in that query and you're good to go.
http://dev.mysql.com/doc/refman/5.1/en/show-create-table.html
If you use Postgresql:
CREATE TABLE LIKE table_name
http://www.postgresql.org/docs/8.1/static/sql-createtable.html
SELECT * INTO Table_Copy
FROM Table
where 1=2
This worked very well, when i tried to create a replica of the table without any data's.
SELECT * INTO Table_Copy
FROM Table
This will create a replica with the data's too.
This can help you:
CREATE TABLE foo AS SELECT...
Read more here
select * into newtablename from sourcetablename
go
truncate newtablename
go
That will result in an exact copy but it also copies the data at first which you remove with the truncate statement.
create table <new table name> as select * from <old tale name from which you would like to extract data>
It will create a new table with a different name but will copy all existing data from the old table to new table.
in postgres you can use INHERITS or LIKE keyword to make replica of a table(only copies structure of the table)
CREATE TABLE client_new (LIKE client);
or
CREATE TABLE client_new () INHERITS (client)
Use of INHERITS creates a persistent relationship between the new child table and its parent table(s). Schema modifications to the parent(s) normally propagate to children as well, and by default the data of the child table is included in scans of the parent(s).
LIKE clause specifies a table from which the new table automatically copies all column names, their data types, and their not-null constraints.Unlike INHERITS, the new table and original table are completely decoupled after creation is complete. Changes to the original table will not be applied to the new table, and it is not possible to include data of the new table in scans of the original table.