SQL Server - Create Copy of Multiple Tables in Same Database - sql-server

I need to duplicate several tables in a single database. Basically we have an old dot net nuke portal that needs to be split and our host limits us to a single database. So we just want to take the existing tables but copy them with an exact duplicate but different table prefix name (e.g. EEPTL_Users to JBPTL_Users).
I can use 'script to - create' to make the proper table structure but how do I do the proper inserts when I need to specify the primary keys but want the column to be an auto-incrementing identiy?
Is there a tool for doing what I need?

SET IDENTITY_INSERT [table name] ON
INSERTS
SET IDENTITY_INSERT [table name] OFf

Related

Script out objects from DB with identity columns replaced by variables to copy object to other environment

I have multiple environments for an application, like DEV, TEST, UAT, PROD.
I would need to copy some objects from the database created in UAT environment into PROD environment. The object is stored in the DB spreaded to multiple tables. Most of the tables have PK as IDENTITY (autogenerated). I don't have access to PROD db data (it is sensitive data in general).
What I need is to generate SQL script for inserting the object that does not preserve the values of Ids but uses the Ids assigned in target environment to related records.
Example: let's say object Order composed of [Order] and list of [OrderItem] rows. I would need to select one specific row in [Order] table, specify that also related rows from [OrderItem] should be included and generate script that would insert new row for [Order], get the value of assigned Order.Id, keep it in a variable and use it for inserting [OrderItem] rows. This is trivial example, my object is spreaded to many more tables, but the concept is the same.
Is there any tool for doing this? All scripting out utilities I tried preserve values of Identity columns.
I think you would need to write custom code to achieve the need of first loading to parent table, followed by loading to child table based on SCOPE_IDENTITY() value.
Instead, if you don't have huge number of rows, I would suggest you to follow below steps:
Load data from Production to another environment using SSIS package or another means
Add the foreign key constraint in the child table to have UPDATE CASCADE
ALTER TABLE ChildTable ADD CONSTRAINT FK_OrderDetail_Order FOREIGN KEY([OrderID])
REFERENCES [dbo].[Order] ([OrderID])
ON UPDATE CASCADE
Now, Update the identity value to another value using some logic
set identity_insert Order ON
UPDATE Order SET OrderID = OrderID + 1000000 -- Have some other logic for random generation
set identity_Insert Order OFF
Now, automatically the child table will get updated with new OrderID.
UPDATE
This SO link talks about automating the code generation for INSERT scripts: What is the best way to auto-generate INSERT statements for a SQL Server table?
Also, I would suggest you to first script out parent tables, followed by child tables.
You can identify parent,child tables using the below script. You need to generate scripts now as per the parent, child depency.
select object_name(parent_object_id) as childTable, object_name(referenced_object_id) as parentTable
from sys.foreign_keys
WHERE object_name(parent_object_id) IN 'Your comma separated list of tables'

Take complete backup of table with index and keys in SQL Server

I have a table (i.e. tbl_test) with 46 index and 42 keys.
I have taken backup via this command:
select *
into tbl_test_bkp_18112019
from tbl_test
But it is unable to copy index and keys in the backup table. I want to take a complete backup of the table with index and keys. Please suggest how.
Select * into - Does not copy indexes, constraints, etc.
You should generate a script from SQL server management studio by right-clicking on the desired table -> Script table as -> create to -> New query windows.
Change the table name as needed and run the script.
This will create a new table with the same structure, indexes, constraints, etc.
If you need data as well then you can insert from the orignal table to this new table using insert command
Insert newtablename select columns from oldtablename
You can Try Task > Generate Script and select only table with data and check in SQL Management Studio

view created table in microsoft sql server

I am running part of a query in Microsoft SQL server management studio
Select Table1.Column1
into #Table2
from Table1
now it has created the table but I actually want to view this table with my eyes but I cannot seem to find where the table is stored. Please could someone help me find it?
That is a temporary table. It will be created in the tempdb system database and you can see it by going to tempdb -> Temporary Tables.
Any tables where its name start with # is a Temporary Table. Exactly as the name suggests, it's temporary, and only exists for the same time the connection that created it does (or it is dropped).
If you want to view the data from a temporary table, you would do so like any other table SELECT * FROM #Table2;. .
I imagine what your really after is to not use a temporary table, so drop the # from the name, and the new table will be created in the database you are connected to.

How To change the column order of An Existing Table in SQL Server 2008

I have situation where I need to change the order of the columns/adding new columns for existing Table in SQL Server 2008.
Existing column
MemberName
MemberAddress
Member_ID(pk)
and I want this order
Member_ID(pk)
MemberName
MemberAddress
I got the answer for the same ,
Go on SQL Server → Tools → Options → Designers → Table and Database Designers and unselect Prevent saving changes that require table re-creation
2- Open table design view and that scroll your column up and down and save your changes.
It is not possible with ALTER statement. If you wish to have the columns in a specific order, you will have to create a newtable, use INSERT INTO newtable (col-x,col-a,col-b) SELECT col-x,col-a,col-b FROM oldtable to transfer the data from the oldtable to the newtable, delete the oldtable and rename the newtable to the oldtable name.
This is not necessarily recommended because it does not matter which order the columns are in the database table. When you use a SELECT statement, you can name the columns and have them returned to you in the order that you desire.
If your table doesn't have any records you can just drop then create your table.
If it has records you can do it using your SQL Server Management Studio.
Just click your table > right click > click Design then you can now arrange the order of the columns by dragging the fields on the order that you want then click save.
Best Regards
I tried this and dont see any way of doing it.
here is my approach for it.
Right click on table and Script table for Create and have this on
one of the SQL Query window,
EXEC sp_rename 'Employee', 'Employee1' -- Original table name is Employee
Execute the Employee create script, make sure you arrange the columns in the way you need.
INSERT INTO TABLE2 SELECT * FROM TABLE1.
-- Insert into Employee select Name, Company from Employee1
DROP table Employee1.
Relying on column order is generally a bad idea in SQL. SQL is based on Relational theory where order is never guaranteed - by design. You should treat all your columns and rows as having no order and then change your queries to provide the correct results:
For Columns:
Try not to use SELECT *, but instead specify the order of columns in the select list as in: SELECT Member_ID, MemberName, MemberAddress from TableName. This will guarantee order and will ease maintenance if columns get added.
For Rows:
Row order in your result set is only guaranteed if you specify the ORDER BY clause.
If no ORDER BY clause is specified the result set may differ as the Query Plan might differ or the database pages might have changed.
Hope this helps...
This can be an issue when using Source Control and automated deployments to a shared development environment. Where I work we have a very large sample DB on our development tier to work with (a subset of our production data).
Recently I did some work to remove one column from a table and then add some extra ones on the end. I then had to undo my column removal so I re-added it on the end which means the table and all references are correct in the environment but the Source Control automated deployment will no longer work because it complains about the table definition changing.
The real problem here is that the table + indexes are ~120GB and the environment only has ~60GB free so I'll need to either:
a) Rename the existing columns which are in the wrong order, add new columns in the right order, update the data then drop the old columns
OR
b) Rename the table, create a new table with the correct order, insert to the new table from the old and delete from the old as I go along
The SSMS/TFS Schema compare option of using a temp table won't work because there isn't enough room on disc to do it.
I'm not trying to say this is the best way to go about things or that column order really matters, just that I have a scenario where it is an issue and I'm sharing the options I've thought of to fix the issue
SQL query to change the id column into first:
ALTER TABLE `student` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT FIRST;
or by using:
ALTER TABLE `student` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT AFTER 'column_name'

What is the equivalent of 'CREATE TABLE ... LIKE ..." in SQL Server

I am working with SQL Server (I am a SQL Server noob) and trying to alter a table. I want to CREATE TABLE LIKE to safely store data while I drop keys and constraints and all the other rigamorole that SQL Server seems to require when altering on the original table but I have not been able to find a match to that command...
you want to recreate the same structure?
how about this
SELECT *
into test
FROM myRealTable
where 0=1
no data will be inserted into the new table
You can do
SELECT * INTO #MyTable_tmp FROM MyTable
Then modify your MyTable, and copy your data back in. Other approaches I've seen is to create a new table call it Mytable_Tmp (Not a temp table), which will be your new table.
Then copy your data doing any migrations you need. Then you will drop the original table and do a rename on Mytable.
Or you can get one of the many excellant tools that compare databases and generate difference scripts or VSTS DB Edition (Comes with developer) and you can do a diff script from a project file to a DB.
Edit
When you run SELECT * INTO #MyTable FROM MyTable, SQL Server creates a new temporary table called #MyTable that matches each column and data type from your select clause. In this case we are selecting * so it will match MyTable. This only creates the columns it doesn't copy defaults, constraints indexes or anything else.

Resources