Script for deleting database, dirs, Then restore default database, dirs - sql

OS: Windows Server 2012 using SQL Server 2012
I have recently taken control of a training environment, and I need a script that will perform the following:
i. Delete the current database from SQL 2012
ii. Delete 2x windows DIR's
iii. Restore a default state database to SQL2012
iv. Copy 2x Windows Dirs back to the recently deleted DIR
Any help would be appreciated :)

This should give you a good starting point
DECLARE #cmd varchar(8000)
DECLARE #Copycmd varchar(8000)
DECLARE #DeleteDir varchar(256)
SET #DeleteDir = 'C:\Test\'
SET #Deletecmd = 'RMDIR ' + #DeleteDir
SET #CopyCMD = 'xcopy "C:\1\*" "C:\2\" /i /s /e /h /T'
EXEC master.dbo.xp_cmdshell #Deletecmd
GO
USE [master]
GO
ALTER DATABASE [my_db_name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
DROP DATABASE [my_db_name]
GO
RESTORE DATABASE my_db_name from disk='d:\backups\my_backups.bak' with file=1
GO
EXEC master.dbo.xp_cmdshell #CopyCMD

Related

How do i backup one specific database from my database server

Hi i want to backup one database of my database server using a bat and a sql file.
sqlcmd -S HEIST-BERG-SL\SQLEXPRESS -E -Q "C:\SALTO\Automatic Backups\scripts\backupDB.sql"
PAUSE
currently i'm missing something in this code to get my specific database called "Salto_Test" when i run the code above i backup all of my databases on the server and thats not what i want.
SQL
declare #datstr as varchar(100)=''
declare #currdate as datetime=getdate()
set #datstr=cast(DATEPART(YYYY,#currDate) as varchar(5))+right('00'+cast(DATEPART(MM,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(DD,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(HH,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(MINUTE,#currDate) as varchar(5)),2)
declare #path as varchar(500)='C:\SALTO\Automatic Backups\Salto_Test_db_' + #datstr +'.BAK'
backup database Salto_Test to disk= #path
If Database name is known then why go for the while loop and query string you can directly write query, Replace your SQL File code by below.
declare #datstr as varchar(100)=''
declare #currdate as datetime=getdate()
set #datstr=cast(DATEPART(YYYY,#currDate) as varchar(5))+right('00'+cast(DATEPART(MM,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(DD,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(HH,#currDate)as varchar(5)),2)+right('00'+cast(DATEPART(MINUTE,#currDate) as varchar(5)),2)
declare #path as varchar(500)='C:\SALTO\Automatic Backups\Salto_Test_db_' + #datstr +'.BAK'
backup database Salto_Test to disk= #path

Command to read/import .dbf files from local system into SQL Server 2016 64 bit

I am trying to import .dbf files into SQL Server 2016 64bit. For this I installed Microsoft Visual FoxPro. Below setup works for 32bit version of SQL Server but not to 64bit. I also tried changing the driver's name eg: Microsoft.Jet.OLEDB.4.0, Microsoft.ACE.OLEDB.16.0, etc. but no luck.
USE [master]
GO
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
USE [master]
GO
EXEC master.dbo.sp_MSset_oledb_prop N'VFPOLEDB', N'AllowInProcess', 1
GO
And then,
DECLARE #sql AS NVARCHAR(200),
#path AS NVARCHAR(200),
#table AS NVARCHAR(200)
SET #path = 'C:\Users\sid\Downloads\VPF\'
SET #table = 'dmfiles'
SET #sql = 'Select * from openrowset(''VFPOLEDB'','''+#path+''';'''';'''',''select * from '+#table+'.dbf'')'
EXEC sp_executesql #sql
Also tried creating a Linked server type of cmd:
SELECT *
FROM OPENROWSET ('MICROSOFT.ACE.OLEDB.12.0','dBase
5.0;HDR=YES;IMEX=2;DATABASE=\Dbf Directory\','SELECT * FROM dbf_filename.dbf')
When I either try to open Linked server, run any command, SQL Server just says executing and never shows any result nor throws error.
I tried using DBF Viewer 2000 to convert .dbf to .sql and ran them against a DB but, running above SQL (if worked fine) would be great for my automation script.
Help is much appreciated!

How can i use master db in stored procedures

I'm trying to create restore db proc. I encountered a problem because i cannot use the command 'use master'. I have try with dynamic SQL but there is no result:
My code:
alter proc dbo.RestoreDB
(
#location as varchar(4000)
)
as
begin
declare #setMasterDb as varchar(400) = 'use master'
exec (#setMasterDb);
ALTER DATABASE [testDb] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
RESTORE DATABASE [testDb] FROM DISK = #location WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 5
ALTER DATABASE [testDb] SET MULTI_USER
end
GO
Is there workaround?
Switching database contexts (USE someDBName) in the middle of a Stored Proc (or function) is not allowed. Also, you do not need to be pointed at the master db context to run a BACKUP/RESTORE, you can be pointed to almost any DB. To fix your issue, just remove your DB switching and point your query window any DB except the one you want to restore.
EDIT: Updated to point to any DB EXCEPT the one you're trying to restore. Thanks to #DMason for that comment.

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

I am actually trying to make a script (in Sql Server 2008) to restore one database from one backup file. I made the following code and I am getting an error -
Msg 3101, Level 16, State 1, Line 3
Exclusive access could not be obtained because
the database is in use.
Msg 3013, Level 16, State 1, Line 3
RESTORE DATABASE is terminating abnormally.
How do I fix this problem ?
IF DB_ID('AdventureWorksDW') IS NOT NULL
BEGIN
RESTORE DATABASE [AdventureWorksDW]
FILE = N'AdventureWorksDW_Data'
FROM
DISK = N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\Backup\AdventureWorksDW.bak'
WITH FILE = 1,
MOVE N'AdventureWorksDW_Data'
TO N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\DATA\AdventureWorksDW.mdf',
MOVE N'AdventureWorksDW_Log'
TO N'C:\Program Files\Microsoft SQL Server\
MSSQL10_50.SS2008\MSSQL\DATA\AdventureWorksDW_0.LDF',
NOUNLOAD, STATS = 10
END
Set the path to restore the file.
Click "Options" on the left hand side.
Uncheck "Take tail-log backup before restoring"
Tick the check box - "Close existing connections to destination database".
Click OK.
I'll assume that if you're restoring a db, you don't care about any existing transactions on that db. Right? If so, this should work for you:
USE master
GO
ALTER DATABASE AdventureWorksDW
SET SINGLE_USER
--This rolls back all uncommitted transactions in the db.
WITH ROLLBACK IMMEDIATE
GO
RESTORE DATABASE AdventureWorksDW
FROM ...
...
GO
Now, one additional item to be aware. After you set the db into single user mode, someone else may attempt to connect to the db. If they succeed, you won't be able to proceed with your restore. It's a race! My suggestion is to run all three statements at once.
execute this query before restoring database:
alter database [YourDBName]
set offline with rollback immediate
and this one after restoring:
alter database [YourDBName]
set online
For me, the solution is:
Check Overwrite the existing database(WITH REPLACE) in optoins tab at left hand side.
Uncheck all other options.
Select source and destination database.
Click ok.
That's it.
taking original db to offline worked for me
Use the following script to find and kill all the opened connections to the database before restoring database.
declare #sql as varchar(20), #spid as int
select #spid = min(spid) from master..sysprocesses where dbid = db_id('<database_name>')
and spid != ##spid
while (#spid is not null)
begin
print 'Killing process ' + cast(#spid as varchar) + ' ...'
set #sql = 'kill ' + cast(#spid as varchar)
exec (#sql)
select
#spid = min(spid)
from
master..sysprocesses
where
dbid = db_id('<database_name>')
and spid != ##spid
end
print 'Process completed...'
Hope this will help...
I just restarted the sqlexpress service and then the restore completed fine
I think you just need to set the db to single user mode before attempting to restore, like below, just make sure you're using master
USE master
GO
ALTER DATABASE AdventureWorksDW
SET SINGLE_USER
Use Master
alter database databasename set offline with rollback immediate;
--Do Actual Restore
RESTORE DATABASE databasename
FROM DISK = 'path of bak file'
WITH MOVE 'datafile_data' TO 'D:\newDATA\data.mdf',
MOVE 'logfile_Log' TO 'D:\newDATA\DATA_log.ldf',replace
alter database databasename set online with rollback immediate;
GO
I experienced this issue when trying to restore a database on MS SQL Server 2012.
Here's what worked for me:
I had to first run the RESTORE FILELISTONLY command below on the backup file to list the logical file names:
RESTORE FILELISTONLY
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
This displayed the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively:
LogicalName PhysicalName
com.my_db C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf
com.my_db_log C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf
All I had to do was to simply replace the LogicalName and the corresponding PhysicalName of the Data and Log files for the database respectively in my database restore script:
USE master;
GO
ALTER DATABASE my_db SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
RESTORE DATABASE my_db
FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup\my_db_backup.bak'
WITH REPLACE,
MOVE 'com.my_db' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db.mdf',
MOVE 'com.my_db_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\com.my_db_log.ldf'
GO
ALTER DATABASE my_db SET MULTI_USER;
GO
And the Database Restore task ran successfully:
That's all.
I hope this helps
Setting the DB to single-user mode didn't work for me, but taking it offline, and then bringing it back online did work. It's in the right-click menu of the DB, under Tasks.
Be sure to check the 'Drop All Active Connections' option in the dialog.
Vinu M Shankar's solution worked for me.
But I had to check the: "Take tail-log backup before restoring" checkbox for mine to work.
Here's a way I am doing database restore from production to development:
NOTE: I am doing it via SSAS job to push production database to development daily:
Step1: Delete previous day backup in development:
declare #sql varchar(1024);
set #sql = 'DEL C:\ProdAEandAEXdataBACKUP\AE11.bak'
exec master..xp_cmdshell #sql
Step2: Copy production database to development:
declare #cmdstring varchar(1000)
set #cmdstring = 'copy \\Share\SQLDBBackup\AE11.bak C:\ProdAEandAEXdataBACKUP'
exec master..xp_cmdshell #cmdstring
Step3: Restore by running .sql script
SQLCMD -E -S dev-erpdata1 -b -i "C:\ProdAEandAEXdataBACKUP\AE11_Restore.sql"
Code that is within AE11_Restore.sql file:
RESTORE DATABASE AE11
FROM DISK = N'C:\ProdAEandAEXdataBACKUP\AE11.bak'
WITH MOVE 'AE11' TO 'E:\SQL_DATA\AE11.mdf',
MOVE 'AE11_log' TO 'D:\SQL_LOGS\AE11.ldf',
RECOVERY;
I got this error when there was not enough disk space to restore Db. Cleaning some space solved it.
Solution 1 : Re-start SQL services and try to restore DB
Solution 2 : Re-start system / server and try to restore DB
Solution 3 : Take back of current DB, Delete the current/destination DB and try to restore DB.
I got this error when unbeknownst to me, someone else was connected to the database in another SSMS session. After I signed them out the restore completed successfully.
In my case although i tried all of the above solutions, the thing that worked, was to restart SSMS.

restore sql server from .bak file Exclusive access could not be obtained

I am trying to restore my sql using bak file
I am getting error
Exclusive access could not be obtained because the database is in use
I tried
USE [master]
ALTER DATABASE myDB
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
and run the query
USE [master] RESTORE DATABASE myDB
FROM DISK = 'C:\MyDatabase.bak' WITH FILE = 1, NOUNLOAD, STATS = 10
I also tried from restore wizard with same result.
Exclusive access could not be obtained because the database is in use.
Method 1
declare #sql as varchar(20), #spid as int
select #spid = min(spid) from master..sysprocesses where dbid = db_id('<database_name>') and spid != ##spid
while (#spid is not null)
begin
print 'Killing process ' + cast(#spid as varchar) + ' ...'
set #sql = 'kill ' + cast(#spid as varchar)
exec (#sql)
select
#spid = min(spid)
from
master..sysprocesses
where
dbid = db_id('<database_name>')
and spid != ##spid
end
print 'Process completed...'
Method 2
alter database database_name
set offline with rollback immediate
alter database database_name
set online
go
Don't need to write any query to solve this problem.
I had the same problem several times and solve it by this method:
when you are restoring database
Go to Option tab in Restore database window
Check (Overwrite the existing database (WITH REPLACE))
Check (Close existing connections to destination database)
Then click OK
Restore database is starting...
Anyone that has had the issues listed above, and none of the advice works.. Just turn off the Taillog backup under 'options'..
Setting (or leaving) this option on will attempt to take a tail-log of the source database itself (even if your source for the restore is just a file). So if the source database is in use (which if you are doing a copy of a production DB will normally be the case) then the restore fails.
I had this issue when I was trying to restore a production backup to a dev server that already had the database there. I wanted to restore as a copy, which I did by changing the target database name, but the issue was actually with the files. By default, it was trying to overwrite the files that were already there. I fixed the issue by checking the "Relocate all files to folder" in the "Files" page of the restore dialog and choosing a new directory so there wouldn't be file collisions.
None of the above solution did not work for me.
After many trials and errors, I stopped SQL Server Browser and then the restore completed successfully