Copying a table in SQL Server - sql

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

Related

add column to existing table postgres

I have a table1 created in the prod environment. I have to add column to an existing table1.
Im using the function create of replace to create the table with the suitable ddl.
To add the column shall i add it manually on the prod machine and change the ddl.
Or changing only the ddl will do it?
Thank you
As far as i know there is no such thing as a create or replace table syntax. that should only work for functions or views.
Use the ALTER TABLE Table1 ADD NewColumn {DATA_TYPE} command.
The way you phrased your question makes me think you use a 3rd party database version control like liquibase. If that is the case leave the initial create DDL alone and just add it as a separate change. If you change the initial ddl it will only affect new databases.

Copy Table Constraints/Keys along with Data and Structure

I have table "TableA", I want to make a copy of it "TableA_Copy", when I use the below script, it creates Table and data, but Constraints are not copied, is it possible copy the constraints along with Structure and Data
SELECT * INTO TableA_Copy FROM TableA
Note am using SQL Server 2016
Right click on the database and go to tasks->Generate script.
Select the table you want TableA, go to next step and ynder advanced options select data and schema.
Save the script or have it in a new query window.
Once the script is generated, replace TableA with TableA_copy
This way you will get data, schema and all the constraints. Remember to change the name of constraints to avoid any errors.
If you mean programmatically, then yes there are a number of ways in tsql to accomplish this by using the INFORMATION_SCHEMA views. The particular ones you will need for the table/columns are INFORMATION_SCHEMA.TABLES, and INFORMATION_SCHEMA.COLUMNS. For the constraints you can use INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE which will provide you the PK and FKs and INFORMATION_SCHEMA.CHECK_CONSTRAINTS for all check constraints.
Using these you can rebuild the table, complete, for use as you indicate above.

a special case when modifing the database

sometimes i face the following case in my database design,, i wanna to know what is the best practice to handle this case:::
for example i have a specific table and after a while ,, when the database in operation and some real data are already entered.. i need to add some required fields (that supposed not to accept null)..
what is the best practice in this situation..
make the field accept null as (some data already entered in the table ,, and scarify the important constraint )and try to force the user to enter this field through some validation in the code..
truncate all the entered data and reentered them again (tedious work)..
any other suggestions about this issue...
It depends on requirements. If the data to populate existing rows for the new column isn't available immediately then I would generally prefer to create a new table and just populate new rows when the data exists. If and when you have all the data for every row then put the new column into the original table.
If possible i would set a default value for the new column.
e.g. For Varchar
alter table table_name
add column_name varchar(10) not null
constraint column_name_default default ('Test')
After you have updated you could then drop the default
alter table table_name
drop constraint column_name_default
A lot will come down to your requirements.
It depends on your application, your database scheme, your entities.
The best way to go about it is to truncate the data and re - enter it again, but it need not be too tedious an item. Temporary tables and table variables could assist a great deal with this issue. A simple procedure comes to mind to go about it:
In SQL Server Management Studio, Right - click on the table you wish to modify and select Script Table As > CREATE To > New Query Editor Window.
Add a # in front of the table name in the CREATE statement.
Move all records into the temporary table, using something to the effect of:
INSERT INTO #temp SELECT * FROM original
Then run the script to keep all your records into the temporary table.
Truncate your original table, and make any changes necessary.
Right - click on the table and select Script Table As > INSERT To > Clipboard, paste it into your query editor window and modify it to read records from the temporary table, using INSERT .. SELECT.
That's it. Admittedly not quite straightforward, but a well - kept database is almost always worth a slight hassle.

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.

Copy tables from one database to another in SQL Server

I have a database called foo and a database called bar. I have a table in foo called tblFoobar that I want to move (data and all) to database bar from database foo. What is the SQL statement to do this?
SQL Server Management Studio's "Import Data" task (right-click on the DB name, then tasks) will do most of this for you. Run it from the database you want to copy the data into.
If the tables don't exist it will create them for you, but you'll probably have to recreate any indexes and such. If the tables do exist, it will append the new data by default but you can adjust that (edit mappings) so it will delete all existing data.
I use this all the time and it works fairly well.
On SQL Server? and on the same database server? Use three part naming.
INSERT INTO bar..tblFoobar( *fieldlist* )
SELECT *fieldlist* FROM foo..tblFoobar
This just moves the data. If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else.
This should work:
SELECT *
INTO DestinationDB..MyDestinationTable
FROM SourceDB..MySourceTable
It will not copy constraints, defaults or indexes. The table created will not have a clustered index.
Alternatively you could:
INSERT INTO DestinationDB..MyDestinationTable
SELECT * FROM SourceDB..MySourceTable
If your destination table exists and is empty.
If it’s one table only then all you need to do is
Script table definition
Create new table in another database
Update rules, indexes, permissions and such
Import data (several insert into examples are already shown above)
One thing you’ll have to consider is other updates such as migrating other objects in the future. Note that your source and destination tables do not have the same name. This means that you’ll also have to make changes if you dependent objects such as views, stored procedures and other.
Whit one or several objects you can go manually w/o any issues. However, when there are more than just a few updates 3rd party comparison tools come in very handy. Right now I’m using ApexSQL Diff for schema migrations but you can’t go wrong with any other tool out there.
Script the create table in management studio, run that script in bar to create the table. (Right click table in object explorer, script table as, create to...)
INSERT bar.[schema].table SELECT * FROM foo.[schema].table
You can also use the Generate SQL Server Scripts Wizard to help guide the creation of SQL script's that can do the following:
copy the table schema
any constraints (identity, default values, etc)
data within the table
and many other options if needed
Good example workflow for SQL Server 2008 with screen shots shown here.
You may go with this way: ( a general example )
insert into QualityAssuranceDB.dbo.Customers (columnA, ColumnB)
Select columnA, columnB from DeveloperDB.dbo.Customers
Also if you need to generate the column names as well to put in insert clause, use:
select (name + ',') as TableColumns from sys.columns
where object_id = object_id('YourTableName')
Copy the result and paste into query window to represent your table column names and even this will exclude the identity column as well:
select (name + ',') as TableColumns from sys.columns
where object_id = object_id('YourTableName') and is_identity = 0
Remember the script to copy rows will work if the databases belongs to the same location.
You can Try This.
select * into <Destination_table> from <Servername>.<DatabaseName>.dbo.<sourceTable>
Server name is optional if both DB is in same server.
I give you three options:
If they are two databases on the same instance do:
SELECT * INTO My_New_Table FROM [HumanResources].[Department];
If they are two databases on different servers and you have linked servers do:
SELECT * INTO My_New_Table FROM [ServerName].[AdventureWorks2012].[HumanResources].[Department];
If they are two databases on different servers and you don't have linked servers do:
SELECT * INTO My_New_Table
FROM OPENROWSET('SQLNCLI', 'Server=My_Remote_Server;Trusted_Connection=yes;',
'SELECT * FROM AdventureWorks2012.HumanResources.Department');