SQL Server - Create a copy of a database table and place it in the same database? - sql

I have a table ABC in a database DB. I want to create copies of ABC with names ABC_1, ABC_2, ABC_3 in the same DB. How can I do that using either Management Studio (preferably) or SQL queries ?
This is for SQL Server 2008 R2.

Use SELECT ... INTO:
SELECT *
INTO ABC_1
FROM ABC;
This will create a new table ABC_1 that has the same column structure as ABC and contains the same data. Constraints (e.g. keys, default values), however, are -not- copied.
You can run this query multiple times with a different table name each time.
If you don't need to copy the data, only to create a new empty table with the same column structure, add a WHERE clause with a falsy expression:
SELECT *
INTO ABC_1
FROM ABC
WHERE 1 <> 1;

Copy Schema (Generate DDL) through SSMS UI
In SSMS expand your database in Object Explorer, go to Tables, right click on the table you're interested in and select Script Table As, Create To, New Query Editor Window.
Do a find and replace (CTRL + H) to change the table name (i.e. put ABC in the Find What field and ABC_1 in the Replace With then click OK).
Copy Schema through T-SQL
The other answers showing how to do this by SQL also work well, but the difference with this method is you'll also get any indexes, constraints and triggers.
Copy Data
If you want to include data, after creating this table run the below script to copy all data from ABC (keeping the same ID values if you have an identity field):
set identity_insert ABC_1 on
insert into ABC_1 (column1, column2) select column1, column2 from ABC
set identity_insert ABC_1 off

If you want to duplicate the table with all its constraints & keys follows this below steps:
Open the database in SQL Management Studio.
Right-click on the table that you want to duplicate.
Select Script Table as -> Create to -> New Query Editor Window.
This will generate a script to recreate the table in a new query window.
Change the table name and relative keys & constraints in the script.
Execute the script.
Then for copying the data run this below script:
SET IDENTITY_INSERT DuplicateTable ON
INSERT Into DuplicateTable ([Column1], [Column2], [Column3], [Column4],... )
SELECT [Column1], [Column2], [Column3], [Column4],... FROM MainTable
SET IDENTITY_INSERT DuplicateTable OFF

1st option
select *
into ABC_1
from ABC;
2nd option: use SSIS, that is right click on database in object explorer > all tasks > export data
source and target: your DB
source table: ABC
target table: ABC_1 (table will be created)

This is another option:
select top 0 * into <new_table> from <original_table>

You need to write SSIS to copy the table and its data, constraints and triggers. We have in our organization a software called Kal Admin by kalrom Systems that has a free version for downloading (I think that the copy tables feature is optional)

In Case you want to do it N times (may be not practical in real world), you might try this:
declare #counter int
set #counter = 2
declare #tname NVARCHAR(100)
DECLARE #SQString NVARCHAR(MAX)
while(#counter <= 20) -- duplicate 20 times
begin
SET #tname= concat('Table_',#counter)
SET #SQString = 'select * into ' + #tname + ' from Table_1'
EXEC (#SQString)
set #counter = #counter + 1
End

use sql server manegement studio or netcat and that will be easier to manipulate sql

Related

SQL Server can't add, delete, add column?

When I run this in a single batch:
ALTER TABLE SomeTable ADD FOO int NULL;
alter table SomeTable drop column foo
ALTER TABLE SomeTable ADD FOO int NULL;
select top 1 FOO from SomeTable
... why in SQL Management studio is the end result that column FOO does not exist on table SomeTable?
The select statement gives an error, but no statement previous raises an error.
Adding GO statements would fix the issue, but why in a single batch does it act as it does?
"why in SQL Management studio is the end result that column FOO does not exist on table SomeTable?" It isn't. The problem is you are trying to reference a column in the same batch you performed an ALTER on the table you added it to; this results in the parsing error and the entire batch is not run.
Either split the SELECT into a separate batch (use GO in SSMS), or defer the parsing of the SELECT:
EXEC sys.sp_executesql N'SELECT TOP 1 FOO FROM dbo.SomeTable ORDER BY SomeColumn;';

SQL Server: is it possible to script table as UPDATE?

I need to export/script two tables to my local database to a remote anyway.
Anyway I cannot export them as INSERT INTO scripts because I cannot drop them in the remote database and populate them again (because of FK and integrity constraints). So, is it possibile to script tables as UPDATE statements for each row, instead of INSERT INTO? I'm using SQL Server 2008/2012
CREATE TABLE mytable(
ExtractTypeNum INTEGER NOT NULL --PRIMARY KEY
,FileOrderNum VARCHAR(11)
,PrevFileOrderNum VARCHAR(11)
,NextFileOrderNum VARCHAR(11)
,rownum1 INTEGER
,Statusflag1 VARCHAR(9)
);
INSERT INTO mytable(ExtractTypeNum,FileOrderNum,PrevFileOrderNum,NextFileOrderNum,rownum1,Statusflag1)
VALUES (1,'2016-09-191',NULL,'2016-09-192',1,'IsInitial');
INSERT INTO mytable(ExtractTypeNum,FileOrderNum,PrevFileOrderNum,NextFileOrderNum,rownum1,Statusflag1)
VALUES (2,'2016-09-192','2016-09-191','2016-09-201',2,NULL);
INSERT INTO mytable(ExtractTypeNum,FileOrderNum,PrevFileOrderNum,NextFileOrderNum,rownum1,Statusflag1)
VALUES (3,'2016-09-201','2016-09-192','2016-09-211',3,NULL);
select 'Update Table Xyz Set Abc='+Convert(varchar(25),rownum1)+' ' as X,*
from myTable
There is many ways to sync data between databases. As my experience, you can do by 2 main ways:
Using MERGE statement (it supports from mssql 2k8: https://msdn.microsoft.com/en-us/library/bb510625.aspx)
write dynamic query to generate data script for 2 target tables:
Select 'select * into #tmp from dbtarget.tbla where 1<0;' as data
Union
Select 'insert into #tmp values(' + convert(varchar, cola) + ', ' + convert(varchar, colb) + ', ' + convert(varchar, colc) + ');' as data from dbsource.tbla;
run the query above at database source to get output script data.
apply script data to target database.
using MERGE statement to merge data between #tmp table and target table.
Utilize Log Shipping feature to sync data between databases in the same structure and in one domain network.
https://msdn.microsoft.com/en-us/library/ms190640(v=sql.110).aspx
Many thanks to Alfaiz Ahmed this is my final working script:
select 'UPDATE ERGO.DBO.RESIDENZE SET CODISEDERESI='+CONVERT(varchar(50),CODISEDERESI)+
',DESCRIRESIDE='+isnull(CONVERT(varchar(100),''''+replace(DESCRIRESIDE,'''','''''')+''''),'''''')+
',INDIRIRESIDE='+isnull(CONVERT(varchar(100),''''+replace(INDIRIRESIDE,'''','''''')+''''),'''''')+
',NOMERESIDENZ='+isnull(CONVERT(varchar(50),''''+replace(NOMERESIDENZ,'''','''''')+''''),'''''')+
',VIARESIDENZA='+isnull(CONVERT(varchar(50),''''+replace(VIARESIDENZA,'''','''''')+''''),'''''')+
',CAPRESIDENZA='+isnull(CONVERT(varchar(50),''''+CAPRESIDENZA+''''),'''''')+
',CITTARESIDEN='+isnull(CONVERT(varchar(50),''''+replace(CITTARESIDEN,'''','''''')+''''),'''''')+
',EMAILRESIDEN='+isnull(CONVERT(varchar(100),''''+EMAILRESIDEN+''''),'''''')+
' WHERE CODICERESIDE='+CONVERT(varchar(50),CODICERESIDE)
from RESIDENZE
I had to use that replace() function because many Italian names have a single quote in their names so, for example, I wanted string D'AZEGLIO to become D''AZEGLIO in order to be correctly processed by SQL. Finally, before execute the query I press CTRL+SHIFT+F to save the output to a sql file as a generated script.

SQL server convert int field to bit

I have a big database and I should to normalize it. One of the table contains field with type "integer" but it contains only 1 and 0 values. So it is good reason to convert this field to bit type. But when I try to save changes in SQL Server Management Studio it tells me that I can't do it. Also I have many field with values like nvarchar that should be converted to int or float that should be converted to int too.
Moreover I should create migration scripts for all changes so I can update real database without loosing data. Maybe somebody knows useful utility for this?
EDIT: It tells me that I can't update unable without drop it. And I want to update table without losing any data.
SQL version 2014
---Create one Temp. Column
Alter Table [dbo].[Demo2]
Add tempId int
GO
--Copy Data in temp. Coulmn
Update [dbo].[Demo2] set tempId=Id
--Drop column which you want to modify
Alter Table [dbo].[Demo2]
Drop Column Id
Go
--Create again that column with bit type
Alter Table [dbo].[Demo2]
Add Id bit
GO
--copy date back
Update [dbo].[Demo2] set Id=tempId
--drop temp column
Alter Table [dbo].[Demo2]
Drop Column tempId
Go
Here's how to add a new column to a table, set that column to the old column and then remove the old column
CREATE TABLE #test
(inttest int
)
Insert [#test]
( [inttest] )
Values ( 0
)
Insert [#test]
( [inttest] )
Values ( 1
)
Alter Table [#test] Add bittest bit
Update [#test] Set bittest=inttest
Alter Table [#test] Drop Column [inttest]
SELECT * FROM [#test] [T]
To generate migration script you don't need a special utility, SSMS does it pretty well.
Right-click the table in SSMS object explorer. Choose Design item in the context menu. Change the type of the column. In the main menu Table Designer choose item Generate Change Script. Save the generated script to a file, review it and make sure you understand each line in it before you run it on a production system. Adjust the script if needed.
On the other hand, to change the column type from int to bit you can use the ALTER TABLE statement:
ALTER TABLE dbo.TableName
ALTER COLUMN ColumnName bit NOT NULL
Before running this you should check that actual int values are indeed only 0 and 1.
After reading of all comments and posts I found solution in building procedure which will convert passed table and column in required. So I wrote this function
IF EXISTS (select * from dbo.sysobjects where id = object_id(N'IntToBit') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
DROP PROCEDURE IntToBit
GO
IF OBJECT_ID('convertion_table', 'U') IS NOT NULL
DROP TABLE dbo.convertion_table;
go
CREATE TABLE dbo.convertion_table
(
bitTypeColumn bit NOT NULL DEFAULT 0,
intTypeColumnt integer ,
)
go
CREATE procedure IntToBit
#table nvarchar(150),
#column nvarchar(150)
AS
begin
DECLARE #sql nvarchar(4000)
SELECT #sql ='
--copy data to temp table
INSERT INTO convertion_table (bitTypeColumn)
SELECT '+#column +'
FROM ' +#table+'
--Drop column which you want to modify
Alter Table ' +#table+'
Drop Column '+#column +'
--Create again that column with bit type
Alter Table ' +#table+'
Add '+#column +' bit NOT NULL DEFAULT(0)
--copy date back
INSERT INTO '+#table+'('+#column+')
SELECT bitTypeColumn
FROM convertion_table
--cleare temp table
--DELETE bitTypeColumn FROM convertion_table
'
exec sp_executesql #sql
end
GO
and then call it passing field and table name :
exec dbo.IntToBit #table = 'tbl_SystemUsers', #column='intUseLogin';
Special thanks to Chris K and Hitesh Thakor
Simply Use TSql script to modify the table rather than using the designer
ALTER TABLE YourTableNameHere
ALTER COLUMN YourColumnNameHere INT
If you are using sql Server then you might wanna generate script for the table before altering the table so that you dont loose any data ..and you can simply retrieve everything using the script

How to execute sql query when debugging a stored procedure

I'm debugging a stored procedure on SQL Server 2008 and I have this:
INSERT INTO #tempTable (ID, Name)
SELECT ID, Name FROM dbo.MYTABLE WHERE dbo.MYTABLE.Old >= 15
How can I view the data into #tempTable on Debug time?
In SQL Server Management Studio, you can't execute query directly while debugging stored procedure, and that's still not implemented(I think). You can only view the local variables value in Local Debug Window.
There are some work around to see temp table values while in Debugging mode:-
1) In the stored procedure, after insert data into #temptable, add this line of code to get temptable values in xml table varriable where you want to see temptable values. Then you can check the values in Local Debug window in xml format
--inserting data into temp table
INSERT INTO #tempTable (ID, Name)
SELECT ID, Name FROM dbo.MYTABLE WHERE dbo.MYTABLE.Old >= 15
--to see records of temp table
DECLARE #temptable XML
SET #temptable = (SELECT * FROM ##temptable FOR XML AUTO)
2) You can convert local temp table(#temptable) to global temptable(##temptable), so when you insert date in temp table, you can open new query window, and able to see global temp table records using select query.
This blog post describes how to access a temporary table from another session:
http://web.archive.org/web/20180409190701/http://sqlblog.com:80/blogs/paul_white/archive/2010/08/14/viewing-another-session-s-temporary-table.aspx
Alternative you can use two ## in the table name to make the table globally accessible from other sessions: ##tempTable (The table might be locked for reading while your insert is running)
Even though SQL Server Management Studio has some debugging functions , but I find them pretty useless.
I don't think there are any debugging tools out there for SQL Server like Visual Studio, which will give you a step by step information at runtime.
The way normally developers debug sql server code is to use print statement, for stored procedures take the sp definition out declare a variable for each parameter that procedure expects , hardcode the values for variables and execute smaller logical blocks of code to see what's going on where.

T-SQL: Creating a temp Table/ table Variable with Flexible structure

I am working on a reporting project based in SQL but I have restricted access to the DB; I can only make SELECT Queries and insert the data I retrieve into temp Tables/table variables. I cannot create/execute stored procedures or any sort of functions.
The query I am running is meant to pool together all Engineers and the different key skills that they have so that we can later on see what Skills each engineer has or which Engineers fall under a certain skill.
To this end, I am trying to create a table variable/temp table with a flexible structure, a structure based on previously obtained values in the same query.
For E.g.
1st Output:
Adam
Brad
Julio
Martinez
2nd Output (Skill separated by white space):
VOIP
TTS
DBA
Exchange
Server
Create temp table/table variable that uses 1st output as rows and 2nd output as columns or vice versa. I will then populate this new table according to different values on the main DB.
Please advise how this can be done, or provide any other solution to this problem.
Thank you
I believe you can.
First of all you need to create temp table with dynamic structure based on query. It can be done like this:
declare script template:
Set #ScriptTmpl = 'Alter table #tempTable Add [?] varchar(100);
build script that will insert columns you need based on query:
Select #TableScript = #TableScript + Replace(#ScriptTmpl, '?',
ColumnName) From ... Where ...
then execute script and then fill your new table with values from second query
UPD:
here is the full sample of temporary table dynamic creation. I used global temporary table in my sample:
declare #scriptTemplate nvarchar(MAX)
declare #script nvarchar(MAX)
declare #tableTemplate nvarchar(MAX)
SET #tableTemplate = 'create table ##tmptable (?)'
SET #scriptTemplate = '? nvarchar(500),'
SET #script = ''
Drop table ##tmptable
Select #script = #script + Replace(#scriptTemplate, '?', [Name])
From Account
Where name like 'ES_%'
SET #script = LEFT(#script, LEN(#script) - 1)
SET #script = Replace(#tableTemplate, '?', #script)
Select #script
exec(#script)
Select * from ##tmptable
Firstly, you may be able to achieve what you want through pivots, rather than temporary tables.
Secondly, if you really want to create a table with column name "Adam Brad", the solution is dynamic SQL, which you may not be able to do based on your permissions.