Create a procedure with Alter Database option - sql-server

I have more than 30 dbs which are encrypted with TDE. Now I have to make a backup of each db without encryption.
Following step are needed:
- Set encryption off
- Do a full backup of that db
- Set encryption on
(Sry, but I am not so good at coding)
Here an example what I did so far:
use [Testt]
ALTER DATABASE [Testt]
SET ENCRYPTION OFF
Go
BACKUP DATABASE [Testt]
TO DISK = N'J:\Backup\Testt_full.bak ' WITH NOFORMAT,COPY_ONLY, NOINIT,
NAME = N'J:\Testt', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO
GO
use [Testt]
ALTER DATABASE [Testt]
SET ENCRYPTION ON
GO
Is there any easier way to do this for 30 dbs? I thought about a procedure or a cursor

Thank you Claudio Biselli for your help:
I adjusted you cursor part:
DECLARE #dbName nvarchar(MAX) =''
DECLARE #sql nvarchar(MAX) = ''
DECLARE #sql2 nvarchar(MAX) = ''
DECLARE #sql3 nvarchar(MAX) = ''
DECLARE Crs CURSOR LOCAL FOR
SELECT d.name
FROM sys.databases d
INNER JOIN
sys.dm_database_encryption_keys e ON d.database_id = e.database_id
where d.name not like 'tempdb'
OPEN Crs
FETCH NEXT FROM Crs into #dbName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sql= 'use ' + #dbName +
' ALTER DATABASE ' + #dbName + ' SET ENCRYPTION OFF'
select #sql
SET #sql2='BACKUP DATABASE ' + #dbName +
' TO DISK = ''J:\Backup\' + #dbName + '_full.bak'' WITH NOFORMAT, COPY_ONLY, NOINIT, NAME = ''J:\'+ #dbName + ''', SKIP, NOREWIND, NOUNLOAD, STATS = 10'
select #sql2
SET #sql3= 'use ' + #dbName +
' ALTER DATABASE ' + #dbName + ' SET ENCRYPTION ON'
select #sql3
FETCH NEXT FROM Crs into #dbName
END
CLOSE Crs
DEALLOCATE Crs
And it works:)

Store in #tmp your database names
DECLARE #dbName nvarchar(MAX) =''
DECLARE #sql nvarchar(MAX) = ''
DECLARE Crs CURSOR LOCAL FOR
SELECT data
FROM #tmp
OPEN Crs
FETCH NEXT FROM Crs into #dbName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sql= 'use' + #dbName +
'ALTER DATABASE' + #dbName +
'SET ENCRYPTION OFF'
EXEC(#sql)
DECLARE #dName nvarchar(MAX) = 'J:\\' + #dbName
DECLARE #dPath nvarchar(MAX) = 'J:\\Backup\\' + #dbName + '_full.bak'
SET #sql='BACKUP DATABASE ' + #dbName +
'TO DISK = '+ #dPath +' WITH
NOFORMAT,COPY_ONLY, NOINIT,
NAME = '+ #dName +', SKIP, NOREWIND, NOUNLOAD, STATS = 10'
EXEC(#sql)
SET #sql= 'use ' + #dbName +
'ALTER DATABASE ' + #dbName +
'SET ENCRYPTION ON'
EXEC(#sql)
FETCH NEXT FROM Crs into #dbName
END
CLOSE Crs
DEALLOCATE Crs

Related

Need to run a stored procedure on all non system databases

I'm trying to loop through all non system databases and run a stored procedure. This stored procedure exists in all of the user databases.
This is what I have found so far:
DECLARE #command varchar(1000)
SELECT #command = 'USE ? SELECT name FROM sysobjects WHERE xtype = ''U'' ORDER BY name'
USE #command;
GO
EXECUTE Support.CleanIndiciesAndShrinkDatabase;
GO
I get an error this error:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '#command'.
Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure 'Support.CleanIndiciesAndShrinkDatabase'.
Any suggestions on fixing this?
Try the following
DECLARE #command varchar(1000)
DECLARE #spName VARCHAR(50)
SET #spName = 'Support.CleanIndiciesAndShrinkDatabase'
SELECT #command = 'IF ''?'' NOT IN(''master'', ''model'', ''msdb'', ''tempdb'')
BEGIN
USE ?
IF EXISTS(SELECT TOP 1 1 FROM sys.procedures AS P WHERE p.name = ''' + #spName + ''')
BEGIN
PRINT ''running '+ #spName + ' on '' + DB_NAME()
EXEC ' +#spName+'
END
ELSE
BEGIN
PRINT ''' + #spName + ' was on found on database '' + DB_NAME()''
END
END '
EXEC sp_MSforeachdb #command
It will run on all non-system databases.
Now, the error you get means that SQL Server cannot find the stored procedure. You could fix this by creating the stored procedure on any database that does not have it yet and then running it.
So a better query would be
DECLARE #command varchar(1000)
DECLARE #schemaName VARCHAR(50)
DECLARE #spName VARCHAR(50)
SET #schemaName = 'Support'
SET #spName = 'CleanIndiciesAndShrinkDatabase'
SELECT #command = 'IF ''?'' NOT IN(''master'', ''model'', ''msdb'', ''tempdb'')
BEGIN
USE ?
IF NOT EXISTS(SELECT TOP 1 1
FROM sys.procedures AS P
INNER JOIN sys.schemas AS S ON S.schema_id = P.schema_id
WHERE p.name = ''' + #spName + '''
AND s.name = ''' + #schemaName + ''')
BEGIN
PRINT ''creating '+ #spName + ' on '' + DB_NAME()
IF NOT EXISTS ( SELECT TOP 1 1
FROM sys.schemas AS S
WHERE S.name = ''' + #schemaName + ''' )
BEGIN
PRINT ''CREATING SCHEMA ' + #schemaName + '''
EXEC ( '' CREATE SCHEMA ' + #schemaName + ''' );
END;
EXEC ( ''
CREATE PROCEDURE ' + #schemaName + '.' + #spName + '
AS
BEGIN
-- SP CODE GOES HERE
-- SELECT COUNT(*) FROM SYS.TABLES --uncomment this for check
END
'' );
END
PRINT ''running '+ #spName + ' on '' + DB_NAME()
EXEC ' + #schemaName + '.' + #spName +'
END '
EXEC sp_MSforeachdb #command
You can try this:
Create PROC PROC_NAME
AS
BEGIN
DECLARE #name nvarchar(50)
declare #cursor cursor
set #cursor = CURSOR FAST_FORWARD FOR select name from sys.databases where database_id > 4
open #cursor
FETCH NEXT FROM #cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
DECLARE #use nvarchar(50) = 'USE '
SET #use = #use + #name
Declare #query nvarchar(max) = #use + ' exec Your_PROC'
EXEC sp_executesql #query
FETCH NEXT FROM #cursor INTO #name
END
CLOSE #cursor
DEALLOCATE #cursor
END
Try something like this:
DECLARE #DynamicTSQLStatement NVARCHAR(MAX);
SELECT #DynamicTSQLStatement = STUFF
(
(
SELECT 'USE [' + [name] + ']; EXECUTE Support.CleanIndiciesAndShrinkDatabase;'
FROM [sys].[databases]
WHERE [name] NOT IN ('master', 'tempdb', 'model', 'msdb')
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1
,1
,''
);
EXECUTE sp_executesql #DynamicTSQLStatement;

How to Backup and delete SQL Server database if the database created date is more than 3 months

How to Backup and delete SQL Server database if the database created date is more than 3 months
Be careful using something like this, this script could get you in to trouble. Notice I am only selecting the #tsql parameter, I commented out the EXEC so you can see what would be executing first.
/* Create a cursor to iterate through the databases you want to backup and delete */
DECLARE #tsql nvarchar(max)
DECLARE #dbname varchar(500)
DECLARE MyCursor CURSOR STATIC FORWARD_ONLY
FOR
SELECT [name]
FROM sys.databases
WHERE create_date < DATEADD (M, -3, GETDATE())
AND [name] NOT IN ('master', 'model', 'msdb', 'tempdb')
OPEN MyCursor
WHILE (1=1)
BEGIN
DECLARE
#Date varchar(20) = GETDATE()
FETCH NEXT FROM MyCursor INTO #dbname
IF ##FETCH_STATUS <> 0 BREAK
SET #tsql = 'BACKUP DATABASE [' + #dbname + '] TO DISK = N''S:\Backups\' + #dbname + ' ' + #Date + '.bak'' WITH NOFORMAT, NOINIT, SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10'
SELECT #tsql;
-- EXEC sp_executesql #tsql
SET #tsql = 'ALTER DATABASE [' + #dbname + '] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [' + #dbname + ']'
SELECT #tsql
-- EXEC sp_executesql #tsql
END
CLOSE MyCursor;
DEALLOCATE MyCursor;
GO

T-SQL Restore Databases with script and variables

There is something going wrong, but can't find the mistake...
I want to restore a database in a procedure, but can't do this with variables...
DECLARE #sql as NVARCHAR(1000)
DECLARE #targetDBname as NVARCHAR(20) = 'BO_9999'
DECLARE #backupFileNamePath as NVARCHAR(100) = '\\SRV015\C$\temp\BO_1767_Schulung_2016-07-13_22-36-28.bak'
DECLARE #masterDBname as NVARCHAR(20) = 'BO_1767_Schulung'
DECLARE #targetMDFfilePath as NVARCHAR(100) = 'Y:\CADTOOLS\DB\BO_9999.mdf'
DECLARE #masterLogname as NVARCHAR(30)= 'BO_1767_Schulung_log'
DECLARE #targetLogFilePath as NVARCHAR(100) = 'Y:\CADTOOLS\LOG\BO_9999_log.LDF'
SET #sql = '''RESTORE DATABASE ' + #targetDBname
SET #sql = #sql + ' FROM DISK = ''''' + #backupFileNamePath + ''''''
SET #sql = #sql + ' WITH FILE = 1'
SET #sql = #sql + ', MOVE ''''' + #masterDBname + ''''''
SET #sql = #sql + ' TO ''''' + #targetMDFfilePath + ''''''
SET #sql = #sql + ', MOVE ''''' + #masterLogname + ''''''
SET #sql = #sql + ' TO ''''' + #targetLogFilePath + ''''''
SET #sql = #sql + ', NOUNLOAD, REPLACE, STATS = 10'''
PRINT #sql
EXEC (#sql)
--THIS COMMAND RUNS BUT I CANT GET THE COMMAND IN AN EXEC WITH VARIABLES
--RESTORE DATABASE BO_9999 FROM DISK = '\\SRV015\C$\temp\BO_1767_Schulung_2016-07-13_22-36-28.bak' WITH FILE = 1, MOVE 'BO_1767_Schulung' TO 'Y:\CADTOOLS\DB\BO_9999.mdf', MOVE 'BO_1767_Schulung_log' TO 'Y:\CADTOOLS\LOG\BO_9999_log.LDF', NOUNLOAD, REPLACE, STATS = 10
Can anybody help me... was still looking lot's of pages in the net... but couldn't get this run?!
THANKS #all
it runns this way:
RESTORE DATABASE BO_9999 FROM DISK = '\SRV015\C$\temp\BO_1767_Schulung_2016-07-13_22-36-28.bak' WITH FILE = 1, MOVE 'BO_1767_Schulung' TO 'Y:\CADTOOLS\DB\BO_9999.mdf', MOVE 'BO_1767_Schulung_log' TO 'Y:\CADTOOLS\LOG\BO_9999_log.LDF', NOUNLOAD, REPLACE, STATS = 10
and this way:
RESTORE DATABASE #targetDBname FROM DISK = #backupFileNamePath WITH FILE = 1, MOVE #masterDBname TO #targetMDFfilePath, MOVE #masterLogname TO #targetLogFilePath, NOUNLOAD, REPLACE, STATS = 10
but in the end i need it like this to run it on another linked server
EXEC (#sql) at [server\instance]
???

Delete all stored procedures in a specific SQL Server schema

I have hundreds of procedures auto generated by DataSync.
I don't have the time and sense to delete them manually.
They all start with DataSync.
Is there a way to delete all stored procedures where the name start with DataSync.?
Use the information_schema.routines (which is fairly standard across RDBMSs such as MSSQL,Mysql):
If your proc names start "DataSync." then they are probably in a schema, so you can find them with:
select
'DROP PROCEDURE [' + routine_schema + '].[' + routine_name + ']'
from
information_schema.routines where routine_schema = 'DataSync' and routine_type = 'PROCEDURE'
If your proc names start "DataSync" then you can find them with:
select
'DROP PROCEDURE [' + routine_schema + '].[' + routine_name + ']'
from
information_schema.routines where routine_name like 'DataSync%' and routine_type = 'PROCEDURE'
If you wanted to execute all these drop statements, you can build a single execute using FOR XML PATH as follows:
declare #sql varchar(max)
set #sql = (
select
'DROP PROCEDURE [' + routine_schema + '].[' + routine_name + '] '
from
information_schema.routines where routine_schema = 'DataSync' and routine_type = 'PROCEDURE'
FOR XML PATH ('')
)
exec (#sql)
Assuming you mean SQL Server when you specify "SQL" - then the easiest way is this: run this query:
SELECT
name,
DropCmd = 'DROP PROCEDURE DataSync.' + name
FROM sys.procedures
WHERE
schema_id = SCHEMA_ID('DataSync')
and the even "lazier" version would be to use a cursor to do this automatically for you:
DECLARE DropSpCursor CURSOR FAST_FORWARD FOR
SELECT
name
FROM sys.procedures
WHERE schema_id = SCHEMA_ID('DataSync')
DECLARE #StoredProcName sysname
DECLARE #DropStatement NVARCHAR(1000)
OPEN DropSpCursor
FETCH NEXT FROM DropSpCursor INTO #StoredProcName, #SchemaName
WHILE (##fetch_status <> -1)
BEGIN
IF (##fetch_status <> -2)
BEGIN
SET #DropStatement = N'DROP PROCEDURE DataSync.' + #StoredProcName
EXEC(#DropStatement)
END
FETCH NEXT FROM DropSpCursor INTO #StoredProcName
END
CLOSE DropSpCursor
DEALLOCATE DropSpCursor
No need for XML or loops:
declare #sql varchar(max) = ''
select #sql += 'drop procedure [' + routine_schema + '].[' + routine_name + '];'
from information_schema.routines where routine_schema = 'DataSync' and routine_type = 'PROCEDURE'
exec(#sql)
DECLARE #name AS VARCHAR(max)
DECLARE MyCursor CURSOR FAST_FORWARD READ_ONLY FOR
SELECT name FROM sys.objects WHERE type='P' AND schema_id=SCHEMA_ID('DataSync')
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
EXEC('DROP PROCEDURE DataSync.' + #name)
FETCH NEXT FROM MyCursor INTO #name
END
CLOSE MyCursor
DEALLOCATE MyCursor
EDIT: changed where clause since it turned out DataSync is a schema name.
I've been using this short script to clear all SPs from a given schema (when using SQL Server). It iterates direct sys.procedures.
DECLARE #schema VARCHAR(100)
SET #schema = 'DataSync'
DECLARE #CurrentStatement AS VARCHAR(MAX)
SET #CurrentStatement = (SELECT TOP(1) 'DROP PROCEDURE [' + #schema + '].[' + name + ']'
FROM sys.procedures
WHERE schema_id = SCHEMA_ID(#schema))
WHILE #CurrentStatement IS NOT NULL
BEGIN
EXEC (#CurrentStatement)
SET #CurrentStatement = (SELECT TOP(1) 'DROP PROCEDURE [' + #schema + '].[' + name + ']'
FROM sys.procedures
WHERE schema_id = SCHEMA_ID(#schema))
END
The premise is very similar to the answer provided by marc_s; however doesn't utilize a cursor for the iteration. While there's a record in sys.procedures matching our schema, we need to delete it.
try this with sql2012 or above,
this will be help to delete all objects by selected schema
keep 'P' and remove rest for stored procedure only (o.type IN ('P')
DECLARE #MySchemaName VARCHAR(50)='dbo', #sql VARCHAR(MAX)='';
DECLARE #SchemaName VARCHAR(255), #ObjectName VARCHAR(255), #ObjectType VARCHAR(255), #ObjectDesc VARCHAR(255), #Category INT;
DECLARE cur CURSOR FOR
SELECT (s.name)SchemaName, (o.name)ObjectName, (o.type)ObjectType,(o.type_desc)ObjectDesc,(so.category)Category
FROM sys.objects o
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
INNER JOIN sysobjects so ON so.name=o.name
WHERE s.name = #MySchemaName
AND so.category=0
AND o.type IN ('P','PC','U','V','FN','IF','TF','FS','FT','PK','TT')
OPEN cur
FETCH NEXT FROM cur INTO #SchemaName,#ObjectName,#ObjectType,#ObjectDesc,#Category
SET #sql='';
WHILE ##FETCH_STATUS = 0 BEGIN
IF #ObjectType IN('FN', 'IF', 'TF', 'FS', 'FT') SET #sql=#sql+'Drop Function '+#MySchemaName+'.'+#ObjectName+CHAR(13)
IF #ObjectType IN('V') SET #sql=#sql+'Drop View '+#MySchemaName+'.'+#ObjectName+CHAR(13)
IF #ObjectType IN('P') SET #sql=#sql+'Drop Procedure '+#MySchemaName+'.'+#ObjectName+CHAR(13)
IF #ObjectType IN('U') SET #sql=#sql+'Drop Table '+#MySchemaName+'.'+#ObjectName+CHAR(13)
--PRINT #ObjectName + ' | ' + #ObjectType
FETCH NEXT FROM cur INTO #SchemaName,#ObjectName,#ObjectType,#ObjectDesc,#Category
END
CLOSE cur;
DEALLOCATE cur;
SET #sql=#sql+CASE WHEN LEN(#sql)>0 THEN 'Drop Schema '+#MySchemaName+CHAR(13) ELSE '' END
PRINT #sql
EXECUTE (#sql)

What is the best way to copy a database?

When I want to make a copy of a database, I always create a new empty database, and then restore a backup of the existing database into it. However, I'm wondering if this is really the least error-prone, least complicated, and most efficient way to do this?
It is possible to skip the step of creating the empty database. You can create the new database as part of the restore process.
This is actually the easiest and best way I know of to clone a database. You can eliminate errors by scripting the backup and restore process rather than running it through the SQL Server Management Studio
There are two other options you could explore:
Detach the database, copy the .mdf file and re-attach.
Use SQL Server Integration Services (SSIS) to copy all the objects over
I suggest sticking with backup and restore and automating if necessary.
Here's a dynamic sql script I've used in the past. It can be further modified but it will give you the basics. I prefer scripting it to avoid the mistakes you can make using the Management Studio:
Declare #OldDB varchar(100)
Declare #NewDB varchar(100)
Declare #vchBackupPath varchar(255)
Declare #query varchar(8000)
/*Test code to implement
Select #OldDB = 'Pubs'
Select #NewDB = 'Pubs2'
Select #vchBackupPath = '\\dbserver\C$\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\pubs.bak'
*/
SET NOCOUNT ON;
Select #query = 'Create Database ' + #NewDB
exec(#query)
Select #query = '
Declare #vBAKPath varchar(256)
declare #oldMDFName varchar(100)
declare #oldLDFName varchar(100)
declare #newMDFPath varchar(100)
declare #newLDFPath varchar(100)
declare #restQuery varchar(800)
select #vBAKPath = ''' + #vchBackupPath + '''
select #oldLDFName = name from ' + #OldDB +'.dbo.sysfiles where filename like ''%.ldf%''
select #oldMDFName = name from ' + #OldDB +'.dbo.sysfiles where filename like ''%.mdf%''
select #newMDFPath = physical_name from ' + #NewDB +'.sys.database_files where type_desc = ''ROWS''
select #newLDFPath = physical_name from ' + #NewDB +'.sys.database_files where type_desc = ''LOG''
select #restQuery = ''RESTORE DATABASE ' + #NewDB +
' FROM DISK = N'' + '''''''' + #vBAKpath + '''''''' +
'' WITH MOVE N'' + '''''''' + #oldMDFName + '''''''' +
'' TO N'' + '''''''' + #newMDFPath + '''''''' +
'', MOVE N'' + '''''''' + #oldLDFName + '''''''' +
'' TO N'' + '''''''' + #newLDFPath + '''''''' +
'', NOUNLOAD, REPLACE, STATS = 10''
exec(#restQuery)
--print #restQuery'
exec(#query)
Backup and Restore is the most straight-forward way I know. You have to be careful between servers as security credentials don't come with the restored database.
The Publish to Provider functionality has worked great for me. See Scott Gu's Blog Entry.
If you need something really robust look at redgate software's tools here...if you are doing much SQL at all, these are worth the $$.
::================ BackUpAllMyDatabases.cmd ============= START
::BackUpAllMyDatabases.cmd
:: COMMAND LINE BATCH SCRIPT FOR TAKING BACKUP OF ALL DATABASES
::RUN THE SQL SCRIPT VIA THE COMMAND LINE WITH LOGGING
sqlcmd -S localhost -e -i "BackUpAllMyDatabases.sql" -o Result_Of_BackUpAllMyDatabases.log
::VIEW THE RESULTS
Result_Of_BackUpAllMyDatabases.log
::pause
::================ BackUpAllMyDatabases.cmd ============= END
--=================================================BackUpAllMyDatabases.sql start
DECLARE #DBName varchar(255)
DECLARE #DATABASES_Fetch int
DECLARE DATABASES_CURSOR CURSOR FOR
select
DATABASE_NAME = db_name(s_mf.database_id)
from
sys.master_files s_mf
where
-- ONLINE
s_mf.state = 0
-- Only look at databases to which we have access
and has_dbaccess(db_name(s_mf.database_id)) = 1
-- Not master, tempdb or model
--and db_name(s_mf.database_id) not in ('Master','tempdb','model')
group by s_mf.database_id
order by 1
OPEN DATABASES_CURSOR
FETCH NEXT FROM DATABASES_CURSOR INTO #DBName
WHILE ##FETCH_STATUS = 0
BEGIN
declare #DBFileName varchar(256)
set #DBFileName = #DbName + '_' + replace(convert(varchar, getdate(), 112), '-', '.') + '.bak'
--REMEMBER TO PUT HERE THE TRAILING \ FOR THE DIRECTORY !!!
exec ('BACKUP DATABASE [' + #DBName + '] TO DISK = N''D:\DATA\BACKUPS\' +
#DBFileName + ''' WITH NOFORMAT, INIT, NAME = N''' +
#DBName + '-Full Database Backup'', SKIP, NOREWIND, NOUNLOAD, STATS = 100')
FETCH NEXT FROM DATABASES_CURSOR INTO #DBName
END
CLOSE DATABASES_CURSOR
DEALLOCATE DATABASES_CURSOR
--BackUpAllMyDatabases==========================end
--======================RestoreDbFromFile.sql start
-- Restore database from file
-----------------------------------------------------------------
use master
go
declare #backupFileName varchar(100), #restoreDirectory varchar(100),
#databaseDataFilename varchar(100), #databaseLogFilename varchar(100),
#databaseDataFile varchar(100), #databaseLogFile varchar(100),
#databaseName varchar(100), #execSql nvarchar(1000)
-- Set the name of the database to restore
set #databaseName = 'ReplaceDataBaseNameHere'
-- Set the path to the directory containing the database backup
set #restoreDirectory = 'ReplaceRestoreDirectoryHere' -- such as 'c:\temp\'
-- Create the backup file name based on the restore directory, the database name and today's date
#backupFileName = #restoreDirectory + #databaseName + '-' + replace(convert(varchar, getdate(), 110), '-', '.') + '.bak'
-- set #backupFileName = 'D:\DATA\BACKUPS\server.poc_test_fbu_20081016.bak'
-- Get the data file and its path
select #databaseDataFile = rtrim([Name]),
#databaseDataFilename = rtrim([Filename])
from master.dbo.sysaltfiles as files
inner join
master.dbo.sysfilegroups as groups
on
files.groupID = groups.groupID
where DBID = (
select dbid
from master.dbo.sysdatabases
where [Name] = #databaseName
)
-- Get the log file and its path
select #databaseLogFile = rtrim([Name]),
#databaseLogFilename = rtrim([Filename])
from master.dbo.sysaltfiles as files
where DBID = (
select dbid
from master.dbo.sysdatabases
where [Name] = #databaseName
)
and
groupID = 0
print 'Killing active connections to the "' + #databaseName + '" database'
-- Create the sql to kill the active database connections
set #execSql = ''
select #execSql = #execSql + 'kill ' + convert(char(10), spid) + ' '
from master.dbo.sysprocesses
where db_name(dbid) = #databaseName
and
DBID <> 0
and
spid <> ##spid
exec (#execSql)
print 'Restoring "' + #databaseName + '" database from "' + #backupFileName + '" with '
print ' data file "' + #databaseDataFile + '" located at "' + #databaseDataFilename + '"'
print ' log file "' + #databaseLogFile + '" located at "' + #databaseLogFilename + '"'
set #execSql = '
restore database [' + #databaseName + ']
from disk = ''' + #backupFileName + '''
with
file = 1,
move ''' + #databaseDataFile + ''' to ' + '''' + #databaseDataFilename + ''',
move ''' + #databaseLogFile + ''' to ' + '''' + #databaseLogFilename + ''',
norewind,
nounload,
replace'
exec sp_executesql #execSql
exec('use ' + #databaseName)
go
-- If needed, restore the database user associated with the database
/*
exec sp_revokedbaccess 'myDBUser'
go
exec sp_grantdbaccess 'myDBUser', 'myDBUser'
go
exec sp_addrolemember 'db_owner', 'myDBUser'
go
use master
go
*/
--======================RestoreDbFromFile.sql

Resources