Duplicate data from one DB Table to another DB Table? - sql

I want to copy Table DOG from DB ANIMAL1 and copy/create the data to Table DOG in DB ANIMAL2.
The Table needs to duplicate all rows (Primary Key) ID as well.
How do I go about that?
Thanks.

If the two servers are on the same network, you could created a "linked server" from e.g. your target server to your source server, and then you could write something like:
INSERT INTO dbo.DOG(list of columns)
SELECT (list of columns)
FROM SourceServer.ANIMAL2.dbo.DOG
If your ID is an IDENTITY, you have to turn on IDENTITY_INSERT before the command:
SET IDENTITY_INSERT dbo.DOG ON
INSERT INTO dbo.DOG(list of columns)
SELECT (list of columns)
FROM SourceServer.ANIMAL2.dbo.DOG
SET IDENTITY_INSERT dbo.DOG OFF
and turn it back off after the INSERT command ran.

bcp would work fine I think. clearly if the table already contains rows on the target and you are appending more rows from the source, it will complain if you violate the primary key contraint
you don't say if you want to do this once, or lots, if once, then BCP would probably be your best, if all the time, the linked servers, or even replication is probably your best bet

in addition to marc_s' answer, you can also export and import data through SSMS' wizard.

Related

How to copy data from select statement to another database table?

In sql server, I have two servers, each with a database. In the first server (sql server 2005) I wrote select statements which then show data whose column names then match with the tables in the 2nd server (the schema is not the same). This is basically a data migration from 2 servers where the schema is new in the newer server.
But now how can I take the data from the select statement and basically insert that into the new table? Also the new table has auto increment on the ID column, but I want to keep the ID's from the old database because they are used in multiple tables.
Thanks
This is pretty straightforward, but has some fiddly bits that most people don't often use.
The simplest way to migrate the data to the new server would be to create a Linked Server using the instructions at this link.
Once you have the linked server configured (and, for this example, I am assuming that you are creating a link on the new server to point to the old server), I would personally make the SELECT queries into Views on the old server.
Then, on the new server, you would create a query sequence like this:
SET IDENTITY_INSERT MyNewTable1 ON
INSERT INTO MyNewTable1 [Optional field list here]
SELECT [Field List | *]
FROM MyOldServer.MyOldDB.dbo.MyViewForNewTable1
SET IDENTITY_INSERT MyNewTable1 OFF
SET IDENTITY_INSERT MyNewTable2 ON
INSERT INTO MyNewTable2 [Optional field list here]
SELECT [Field List | *]
FROM MyOldServer.MyOldDB.dbo.MyViewForNewTable2
SET IDENTITY_INSERT MyNewTable2 OFF
...
Et Voila. Your data is transferred, with the same Identity values.
To insert from server A to server B, you need a Linked Server.
To keep Identity values the same, you need IDENTITY_INSERT turned on.

Overwrite SQL table within same server

I found this link that could be the solution to my question, but I need some clarification.
I have two DBs on one server, the one DB is a backup. I have a broken table and want to replace the table values/records with the table from the backup DB. Can I use the method from the link above, or is it only if the destination table is empty that I can use the "INSERT INTO destination"?
My goal is to overwrite the table with the backup values.
Since your goal is to replace the entire table with the table from the backup database, you can TRUNCATE the target table and then reload from the backup table using INSERT...SELECT.
You will need to be mindful of foreign key constraints. TRUNCATE is not allowed if FKs reference the table so you will need to use DELETE to empty the table instead.

Update and insert in a bulk move (SQL Server)

I have a pair of databases, one is a live database and one is for testing a configuration for that live database. Both reside on the same server.
I have three tables, Users (PK UserId, FK MainGroupId) and Groups (PK GroupId) and GroupMembers (PK GroupMemberId, FK GroupId and UserId).
The tables are the same schema on both databases however the test database has a set of special test users. Groups is mostly stable, but sometimes we add groups, and sometimes we change column data in the groups. GroupMembers is the same but in the test database refers to the test users.
I need to be able to update the Groups table from the live to test user programmatically. I want to use a bulk copy operation, but to do so I have to delete the Groups table first, which will cause a constraint violation.
I could copy the table in bulk to a dummy table, and then post process by doing an insert of the new rows, and update on the existing rows. However, my problems is that there are about 30 tables like Groups, and I don't want to encode all the column names into the stored procedure in the UPDATE SET method. I'd also like to be able to do it in bulk.
The DBAs are dubious about granting ALTER TABLE permission to temporarily drop the constraints.
Any other suggestions?
SInce both databases are on the same server, why not use a MERGE statement?
select for export and import. If you do it in the right order it should work correctly.

Copying a table in SQL Server

Is it possible to copy a table (with definition, constraints, identity) to a new table?
Generate a CREATE script based on the table
Modify the script to create a different table name
Perform an INSERT from selecting everything from the source table
No, not really, you have to script it out, then change the names
you can do this
select * into NewTable
FROM OldTable
WHERE 1 =2 --if you only want the table without data
but it won't copy any constraints
It's not the most elegant solution, but you could use a tool like the free Database Publishing Wizard from Microsoft.
It creates an SQL script of the table definition including data and including indexes and stuff. But you would have to alter the script manually to change the table name...
Another possibility:
I just found this old answer on SO.
This script is an example to script the constraints of all tables, but you can easily change it to select only the constraints of "your" table.
So, you could do the following:
Create the new table with data like SQLMenace said (select * into NewTable from OldTable)
Add constraints, indexes and stuff by changing this SQL script

SQL: Insert all records from one table to another table without specific the columns

I want to insert all the record from the back up table foo_bk into foo table without specific the columns.
if i try this query
INSERT INTO foo
SELECT *
FROM foo_bk
i'll get error "Insert Error: Column name or number of supplied values does not match table definition."
Is it possible to do bulk insert from one table to another without supply the column name?
I've google it but can't seem to find an answer. all the answer require specific the columns.
You should not ever want to do this. Select * should not be used as the basis for an insert as the columns may get moved around and break your insert (or worse not break your insert but mess up your data. Suppose someone adds a column to the table in the select but not the other table, you code will break. Or suppose someone, for reasons that surpass understanding but frequently happen, decides to do a drop and recreate on a table and move the columns around to a different order. Now your last_name is is the place first_name was in originally and select * will put it in the wrong column in the other table. It is an extremely poor practice to fail to specify columns and the specific mapping of one column to the column you want in the table you are interested in.
Right now you may have several problems, first the two structures don't match directly or second the table being inserted to has an identity column and so even though the insertable columns are a direct match, the table being inserted to has one more column than the other and by not specifying the database assumes you are going to try to insert to that column. Or you might have the same number of columns but one is an identity and thus can't be inserted into (although I think that would be a different error message).
Per this other post: Insert all values of a..., you can do the following:
INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table
It's important to specify the column names as indicated by the other answers.
Use this
SELECT *
INTO new_table_name
FROM current_table_name
You need to have at least the same number of columns and each column has to be defined in exactly the same way, i.e. a varchar column can't be inserted into an int column.
For bulk transfer, check the documentation for the SQL implementation you're using. There are often tools available to bulk transfer data from one table to another. For SqlServer 2005, for example, you could use the SQL Server Import and Export Wizard. Right-click on the database you're trying to move data around in and click Export to access it.
SQL 2008 allows you to forgo specifying column names in your SELECT if you use SELECT INTO rather than INSERT INTO / SELECT:
SELECT *
INTO Foo
FROM Bar
WHERE x=y
The INTO clause does exist in SQL Server 2000-2005, but still requires specifying column names. 2008 appears to add the ability to use SELECT *.
See the MSDN articles on INTO (SQL2005), (SQL2008) for details.
The INTO clause only works if the destination table does not yet exist, however. If you're looking to add records to an existing table, this won't help.
All the answers above, for some reason or another, did not work for me on SQL Server 2012. My situation was I accidently deleted all rows instead of just one row. After our DBA restored the table to dbo.foo_bak, I used the below to restore. NOTE: This only works if the backup table (represented by dbo.foo_bak) and the table that you are writing to (dbo.foo) have the exact same column names.
This is what worked for me using a hybrid of a bunch of different answers:
USE [database_name];
GO
SET IDENTITY_INSERT dbo.foo ON;
GO
INSERT INTO [dbo].[foo]
([rown0]
,[row1]
,[row2]
,[row3]
,...
,[rown])
SELECT * FROM [dbo].[foo_bak];
GO
SET IDENTITY_INSERT dbo.foo OFF;
GO
This version of my answer is helpful if you have primary and foreign keys.
As you probably understood from previous answers, you can't really do what you're after.
I think you can understand the problem SQL Server is experiencing with not knowing how to map the additional/missing columns.
That said, since you mention that the purpose of what you're trying to here is backup, maybe we can work with SQL Server and workaround the issue.
Not knowing your exact scenario makes it impossible to hit with a right answer here, but I assume the following:
You wish to manage a backup/audit process for a table.
You probably have a few of those and wish to avoid altering dependent objects on every column addition/removal.
The backup table may contain additional columns for auditing purposes.
I wish to suggest two options for you:
The efficient practice (IMO) for this can be to detect schema changes using DDL triggers and use them to alter the backup table accordingly. This will enable you to use the 'select * from...' approach, because the column list will be consistent between the two tables.
I have used this approach successfully and you can leverage it to have DDL triggers automatically manage your auditing tables. In my case, I used a naming convention for a table requiring audits and the DDL trigger just managed it on the fly.
Another option that might be useful for your specific scenario is to create a supporting view for the tables aligning the column list. Here's a quick example:
create table foo (id int, name varchar(50))
create table foo_bk (id int, name varchar(50), tagid int)
go
create view vw_foo as select id,name from foo
go
create view vw_foo_bk as select id,name from foo_bk
go
insert into vw_foo
select * from vw_foo_bk
go
drop view vw_foo
drop view vw_foo_bk
drop table foo
drop table foo_bk
go
I hope this helps :)
You could try this:
SELECT * INTO foo FROM foo_bk
This is a valid question for example when wanting to append newly imported rows from an imported csv file of the same raw structure into an existing table which may have DB constraints set up such as PKs and FKs.
I would simply do the following, for example:
INSERT INTO roles select * from new_imported_roles_from_csv_file
I also like this when if any new rows violate uniqueness during this operation, the INSERT will fail, not insert anything and in away 'protect' the target table from bad inbound data.