We have this current database which we need to replace some tables by anther tables from backup database. we are using sql server 2008 r2 and I want to know how to do overwrite or replace current tables by new table having same structures. thanks in advance.
step1:
Restore the backup to the same server with a different name.
Say if your actual database is "MYDB", you can restore the backup and name "MYBD_BKUP" something like that.
You can restore database using SQL server management studio
Right click on Databases>Restore Database
Step2: Once restore is success full, you can delete all the tables (to be deleted) from MYDB
Step3:
transfer table from MYDB_BKUP
USE MYDB
select * into <table1> from MYDB_BKUP.dbo.<table1>
etc.. for each table
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_SCHEMA = 'MySchema' AND TABLE_NAME = 'MyTable'))
BEGIN
DROP TABLE MyTable;
END
put this query in your backup database script, for each table you want to replace. like..
IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE
TABLE_SCHEMA = 'YourSchemaName' AND TABLE_NAME = 'table_staff'))
BEGIN
DROP TABLE table_staff;
END
If u want to replace the whole database with backup database then...
Right Click on Database to which u want to replace
Go to Task
Go to Restore...
check from file radio button
Select backup file
Now your .bak file will show in lower area and check this file by clicking on checkbox
Select options of left side in popup
check checkbox.. override existing
click ok
This will replace your current database with backup database
Related
I want a script that will quickly delete a Test instance of a database and recreate it with only a sample of rows in each table. I know there is no referential integrity issues or other object restraints such as stored procedures linked to records. I have tried the following but it states database in use. I think I am missing something in between the drop and clone. What am I doing wrong here? Or does this have to be split between two scripts?
-- ensure "master" is selected in SSMS
IF EXISTS(select * from sys.databases where name='shoesales_TEST')
ALTER DATABASE shoesales_TEST set single_user with rollback immediate
GO
IF EXISTS(select * from sys.databases where name='shoesales_TEST')
DROP DATABASE shoesales_TEST
GO
DBCC CLONEDATABASE
(
shoesales
, shoesales_TEST
)
GO
ALTER DATABASE shoesales_TEST SET READ_WRITE
GO
USE shoesales_TEST
GO
INSERT INTO shoesales_TEST.dbo.sizesales
SELECT TOP 30 * FROM shoesales.dbo.sizesales
GO
We have two databases one in SQL Server & one in DB2, we have a scenario where we do some data inserts & data updates and deletes in SQL Server & at the same time we also do data inserts updates & deletes in Db2.
We sync data back & forth using some processes, whenever there is a change from SQL Server we sync data to db2 for insert, update & delete, if we have a change in db2 we sync data to SQL Server, we use IBM MQ messages which we dequeue the messages to sync the changes back and forth.
Everything was good until we had some issues of data sync from Db2 to SQL Server, one of our process was down which sync from db2 to SQL Server, so there is an on demand job that runs every night that will do full data refresh from Db2 to SQL Server but we are only doing Merge Update & insert, we are not doing delete as data which is yet to be synced to db2 is also present in SQL Server, so we cannot directly delete as both databases can have more or less records, so data on SQL Server some of them are left orphan, we have a scoping so data which is getting updated in SQL Server cannot be change in db2 and vice versa.
My question is when we are syncing from Db2 to SQL Server, how to identify records that got deleted from db2 only so that we can delete those from SQL Server, we don't want to delete records that are created in SQL Server but yet to be sent to db2, we have 114 tables and we cannot maintain a flag if that is an option to differentiate.
When you said you are synchronizing data back and forth between MS SQL Server and DB2 Server, how are you capturing the changes? If using some CDC tool (IDR, GoldenGate, Informatica), these tools allow you to detect conflicts so you can decide what records to keep or delete.
If you are capturing your changes by an in-house development (triggers or your own log scraper ), you should keep at least the operation type and timestamp in your temporary change data set, so that you can recognize the operation.
If you are comparing the tables and deal with changes, you won't be able to recognize if missing columns at DB2 side represents rows deleted on DB2 side or rows added to SQL side... But you can fix that, by developing a proper change data capture mechanism.
Change tracking on the sql server side might be a viable option (as long as all the tables you would like to sync/"delete from" have a primary key).
With CT you could track which rows, for each table, were created at the sql server side
since the last sync from sql server to db2. Those rows should not be deleted yet:
DELETE
FROM SQL_SERVER_TABLE
WHERE
NOT EXISTS(SELECT * FROM CHANGETABLE())
AND NOT EXISTS(SELECT * FROM DB2_staging)
I would connect SQL to DB2 via linked servers (more there : https://learn.microsoft.com/fr-fr/sql/relational-databases/system-stored-procedures/sp-addlinkedserver-transact-sql?view=sql-server-ver15) and then do queries to find out which record are missing on both sides.
This can be accomplished with OPENQUERY. You can do something like that :
SELECT * FROM YourSqlTable
EXCEPT
SELECT * FROM OPENQUERY(YOURDB2SERVER, 'SELECT * FROM YourDB2Table')
And then the same thing inverted :
SELECT * FROM OPENQUERY(YOURDB2SERVER, 'SELECT * FROM YourDB2Table')
EXCEPT
SELECT * FROM YourSqlTable
You can then send the records on the right server .
If you have a lot of tables to compare you can write these queries with dynamic SQL
DECLARE #TABLENAME nvarchar(200);
DECLARE TABLE_CUR CURSOR FOR
SELECT TABLE_NAME FROM YourDatabaseName.INFORMATION_SCHEMA.TABLES;
OPEN TABLE_CUR
FETCH NEXT FROM TABLE_CUR INTO #TABLENAME;
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #Query nvarchar(MAX);
SET #Query = 'SELECT * FROM OPENQUERY(YOURDB2SERVER, ''SELECT *
FROM '+ #TABLENAME + ' '')
EXCEPT
SELECT * FROM '+ #TABLENAME
-- Don't forget the double '' for openquery
EXEC sp_executeSQL #Query;
SET #Query = 'SELECT * FROM '+ #TABLENAME + '
EXCEPT
SELECT * FROM OPENQUERY(YOURDB2SERVER, ''SELECT *
FROM '+ #TABLENAME + ' '')'
-- Don't forget the double '' for openquery
EXEC sp_executeSQL #Query;
END
CLOSE TABLE_CUR;
DEALLOCATE TABLE_CUR;
Thanks for the suggestions, I am not using CDC, but maintaining changes in a LOG table which are yet to be synced to DB2.
DELETE TGT
FROM [IGP].[LocationType] AS TGT
INNER JOIN #locationType SRC ON
TGT.[LocationTypeCode] = SRC.[LocationTypeCode];
I am first inserting the log table data that are yet to be synced to DB2 into #locationType temp table and delete them from IGP(staging Db2 master data) so the updates & Deletes won't be overridden from IGP staging table data which is Db2 master data.
Now I need to take care of inserts that don't exists in Db2 and there in SQL server but it's not synced from the log table I shouldn't be deleting them as it would be data loss, so I use below merge query
MERGE INTO [dbo].[LocationType] AS TGT
USING [IGP].[LocationType] AS SRC
ON TGT.[LocationTypeCode] = SRC.[LocationTypeCode]
WHEN MATCHED AND (EXISTS
(SELECT TGT.[Description] EXCEPT SELECT SRC.[Description]))
THEN
UPDATE SET TGT.[LocationTypeCode] = SRC.[LocationTypeCode],
TGT.[Description] = SRC.[Description]
WHEN NOT MATCHED THEN
INSERT([LocationTypeCode], [Description])
VALUES([LocationTypeCode], [Description])
WHEN NOT MATCHED BY SOURCE
AND (EXISTS (SELECT TGT.[LocationTypeCode]
EXCEPT SELECT [LocationTypeCode] FROM #locationType)) THEN DELETE;
I use SQL Server 2012 and SQL Server 2008 R2.
I create a script from all object (tables / trigger / stored procedure / function ...) in my database.
I generated this script from SQL Server Management Studio. I can recreate my database with this scrips on the other server. But I miss all diagrams of my database after run my script for create another database.
Therefore, I need create backup script from all diagrams that exist in my database.
I need execute this script on the destination database for recreating all my diagrams.
I found this Link. but i need some thinks that create all script (Insert Command) automatically.
I have found a reasonable solution. The problem is that Management Studio cannot display more that 65535 characters for Non-XML data, and cannot be set to display more than 65535.
See code for documentation :)
Backup script:
-- 1. Read from DB, using XML to workaround the 65535 character limit
declare #definition varbinary(max)
select #definition = definition from dbo.sysdiagrams where name = 'ReportingDBDiagram'
select
'0x' + cast('' as xml).value('xs:hexBinary(sql:variable("#definition") )', 'varchar(max)')
for xml path('')
-- 2. Open the result XML in Management Studio
-- 3. Copy the result
-- 4. Paste this in backup script for #definition variable
Restore script:
declare #definition varbinary(max)
set #definition = 0xD0CF -- Paste 0x0 value from Backup script
-- Create diagram using 'official' Stored Procedure
exec dbo.sp_creatediagram
#diagramname = 'ReportingDBDiagramCopy',
#owner_id = null,
#version = 1,
#definition = #definition
Scripting your database does not include diagrams as they are not server objects in the same way as a table or stored procedure; they exist as data in the sysdiagrams table.
A similar question on SO asked How do you migrate SQL Server Database Diagrams to another Database?
The accepted answer is to copy the contents of the sysdiagrams table to the new database, so you could include the table contents in your script. The answer with the most up-votes has a link to a way of scripting diagrams.
I've tried backing up and then restoring a database to the same server, deleting the diagram I had created (I only had one) and then running the following query:
INSERT INTO database2.dbo.sysdiagrams
(
NAME
,principal_id
,version
,DEFINITION
)
SELECT NAME
,principal_id
,version
,DEFINITION
FROM database1.dbo.sysdiagrams
The diagram was successfully restored, however I did do this on a restored backup, I should really test it with a new database generated from a script.
UPDATE:
I scripted a database and then created a new database from it. When trying to rebuild the diagrams using an INSERT statement I got the error
So although it seems possible it's not trivial to create diagrams in a new database created from a script. Go with the answer given regarding scripting diagrams and modify it for your own needs.
Perhaps you can investigate further and post your own answer :)
Here's a quick & dirty method I use. Since the query window won't display the full varbinary(max) value of the definition field, but the XML editor will, I output the rows to XML as follows:
Run the following query on the server/database that contains the diagrams:
SELECT 'INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('''+name+''','
+CONVERT(varchar(2),principal_id)+','+CONVERT(varchar(2),diagram_id)+','+CONVERT(varchar(2),version)+','
+'0x' + CAST('' as xml).value('xs:hexBinary(sql:column("definition"))','varchar(max)') +')'
FROM RCSQL_ClaimStatus.dbo.sysdiagrams
FOR XML PATH
Click on the generated link to open the XML result, and ctrl-a & ctrl-c to copy all rows generated.
Paste that output back into your query window. I usually paste it between a pair of IDENTITY_INSERT's like this:
--TRUNCATE TABLE sysdiagrams
SET IDENTITY_INSERT sysdiagrams ON;
<row>INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('ERD1',1,1,1,0xD0CF11E0A1B11AE100000...)</row>
<row>INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('ERD2',1,2,1,0xD0CF11E0A1B11AE100000...)</row>
<row>INSERT sysdiagrams(name,principal_id,diagram_id,version,definition) VALUES('ERD3',1,3,1,0xD0CF11E0A1B11AE100000...)</row>
SET IDENTITY_INSERT sysdiagrams OFF;
Remove the row & /row XML tags from your inserts, and run them on the target server. You can truncate the sysdiagrams table if you're replacing all values with new values.
When I run this statement in SQL Server:
USE [master]
GO
ALTER DATABASE <DBName> ADD FILEGROUP <[FGName]>
Where is the corresponding .ndf file created on disk?
When I run that query, it's successful and I am able to find the new file group being added to the sys.filegroups table.
But when I run
select * from sys.database_files
I am not able to find the files created for the new file group. I couldn't find it in the disk as well. What am I doing wrong?
Could somebody help with this..?
Try this:
In SQL Server you will have to explicitly add the .ndf files to the different filegroups. If you dont mention any filegroup then by default it will be added to primary filegroup.
So whenever you add a filegroup it is just a logical name and it does not have any physical location.
use yourDBname
select * from sys.database_files
ALTER DATABASE yourDBname ADD FILE (NAME = name1, FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\DB11.ndf', SIZE=100MB, MAXSIZE=500GB, FILEGROWTH=50);
ALTER DATABASE yourDBname ADD FILEGROUP BusyTables
select * from sys.database_files
How do you add a new schema to a database? I am creating a new table and would like to select my own schema from the properties list, but I don't know how to create it. I am using SQL Server Management 2008.
Use the CREATE SCHEMA syntax or, in SSMS, drill down through Databases -> YourDatabaseName -> Security -> Schemas. Right-click on the Schemas folder and select "New Schema..."
Here's a trick to easily check if the schema already exists, and then create it, in it's own batch, to avoid the error message of trying to create a schema when it's not the only command in a batch.
IF NOT EXISTS (SELECT schema_name
FROM information_schema.schemata
WHERE schema_name = 'newSchemaName' )
BEGIN
EXEC sp_executesql N'CREATE SCHEMA NewSchemaName;';
END
I use something like this:
if schema_id('newSchema') is null
exec('create schema newSchema');
The advantage is if you have this code in a long sql-script you can always execute it with the other code, and its short.
Best way to add schema to your existing table: Right click on the specific table-->Design -->
Under the management studio Right sight see the Properties window and select the schema and click it, see the drop down list and select your schema. After the change the schema save it. Then will see it will chage your schema.
You can try this:
use database
go
declare #temp as int
select #temp = count(1) from sys.schemas where name = 'newSchema'
if #temp = 0
begin
exec ('create SCHEMA temporal')
print 'The schema newSchema was created in database'
end
else
print 'The schema newSchema already exists in database'
go
In SQL Server 2016 SSMS expand 'DATABASNAME' > expand 'SECURITY' > expand 'SCHEMA' ; right click 'SCHEMAS' from the popup left click 'NEW SCHEMAS...' add the name on the window that opens and add an owner i.e dbo click 'OK' button