T-SQL Restore Databases with script and variables - sql-server

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]
???

Related

Is there a function to compress 'bak' file in sql script?

In SQL Server, I want to clear personal info and backup it
Backup original DB
Restore as another DB name
Clear personal info in another DB
Backup another DB
Delete rest files
Zip Backup DB
I finished 1~5. but couldn't find a way to do 6.
I Want to compress bak file to zip here.
For instance, below code can be used in Powershell script. Is there a way to use this .Net function in SQL script?
[System.IO.Compression.ZipFile]::CreateFromDirectory($CurrentPath, $DeployHistoryFilePath)
Below is my full script.
DECLARE #DBName NVARCHAR(MAX) = N'TestDB'
DECLARE #BackupPath NVARCHAR(MAX) = N'D:\Database\Backup'
EXEC ('master.dbo.xp_create_subdir N'''+ #BackupPath +'''')
DECLARE #BackupName NVARCHAR(MAX) = N'OnCube_' + REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(MAX), GETDATE(), 120), N'-', N''), N':', N''), N' ', N'_')
DECLARE #DiskFile NVARCHAR(MAX) = #BackupPath + N'\' + #BackupName + N'.bak'
BACKUP DATABASE #DBName TO DISK = #DiskFile
DECLARE #SQL NVARCHAR(MAX) = 'SELECT TOP (1) #OriginalMdf = name FROM ' + #DBName + '.sys.database_files WHERE file_id = 1'
DECLARE #OriginalMdf NVARCHAR(MAX)
EXEC sp_executesql #SQL, N'#OriginalMdf NVARCHAR(MAX) OUT', #OriginalMdf out
SET #SQL = 'SELECT TOP (1) #OriginalLdf = name FROM ' + #DBName + '.sys.database_files WHERE file_id = 2'
DECLARE #OriginalLdf NVARCHAR(MAX)
EXEC sp_executesql #SQL, N'#OriginalLdf NVARCHAR(MAX) OUT', #OriginalLdf out
DECLARE #PartialMdf NVARCHAR(MAX) = #BackupPath + N'\' + #BackupName + N'.mdf'
DECLARE #PartialLdf NVARCHAR(MAX) = #BackupPath + N'\' + #BackupName + N'_0.ldf'
RESTORE FILELISTONLY FROM DISK = #DiskFile
RESTORE DATABASE #BackupName
FROM DISK = #DiskFile
WITH MOVE #OriginalMdf TO #PartialMdf,
MOVE #OriginalLdf TO #PartialLdf
EXEC (N'
USE [' + #BackupName + ']
UPDATE Person
SET
PatientNo = NULL
, PatientName = N''Cleared'' + CONVERT(NVARCHAR(MAX), RawID)
, RoomNo = NULL
, BedNo = NULL
, Birthday = NULL
, Sex = NULL
, Address = NULL
, AdmitDate = NULL
, AdmitNo = NULL
, Description = NULL
, DischargedDate = NULL
')
DECLARE #ClearedDiskFile NVARCHAR(MAX) = #BackupPath + N'\' + #BackupName + N'_PatientInfoCleared.bak'
BACKUP DATABASE #BackupName TO DISK = #ClearedDiskFile
EXEC('DROP DATABASE [' + #BackupName + ']')
EXEC ('xp_cmdshell ''del "' + #DiskFile + '"''')
-- I Want to compress bak file to zip here
-- For instance, below code can be used in Powershell script. Is there a way to use this .Net function in SQL script?
-- [System.IO.Compression.ZipFile]::CreateFromDirectory($CurrentPath, $DeployHistoryFilePath)
PRINT N'Success to make ' + #ClearedDiskFile + '. Patient informations are all cleared'
Is there a way to use this .Net function in SQL script?
Yes, you can use SQL CLR with C#
see samples Using 7-zip and SharpZipLib here:
also , you can create zip file from SQL without Powershell script:
Create zip file from SQL Server

Create a procedure with Alter Database option

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

Using EXEC to create stored procedure to run update string column in SQL Server 2008

I have the following modification of my stored procedure:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spTMSA_Test_Run]
#TableName nvarchar(200) = 'MyTable',
#Parent int = 1145,
#Name nvarchar(100) = '''Test''',
#KPI nvarchar(max) = '''Test''',
#IDCount int = 1137
AS
BEGIN
EXEC('UPDATE ' + #TableName + ' SET Parent = ' + #Parent + ', Name = ' + #Name + ' , KPI = ' + #KPI + ' WHERE IDCount = ' + #IDCount)
END
This procedure is executed successfully if I gave ''' before and after the string value. In case I left ' before and after the string value it will cause error.
Please help me find the reason why and solution as well. Thanks
This procedure is an open door for SQL injection attacks.
Unless you have a really good reason why you need it to create dynamic SQL, I would suggest avoiding it.
If you can't avoid using dynamic sql, the least you can do is to use quotename to keep your procedure a little safer.
As to the problem you state in your question - just move the ''' to the query body:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spTMSA_Test_Run]
#TableName nvarchar(200) = 'MyTable',
#Parent int = 1145,
#Name nvarchar(100) = 'Test',
#KPI nvarchar(max) = 'Test',
#IDCount int = 1137
AS
BEGIN
EXEC('UPDATE QUOTENAME(' + #TableName + ')
SET Parent = ' + #Parent + ',
Name = ''' + #Name + ''' ,
KPI = ''' + #KPI + '''
WHERE IDCount = ' + #IDCount)
END
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spTMSA_Test_Run]
#TableName nvarchar(200) = 'MyTable',
#Parent int = 1145,
#Name nvarchar(100) = '''Test''',
#KPI nvarchar(max) = '''Test''',
#IDCount int = 1137
AS
BEGIN
  declare #sql nvarchar(4000)
  set #sql='UPDATE ' + #TableName + ' SET Parent = ' + #Parent + ', Name = ' + #Name + ' , KPI = ' + #KPI + ' WHERE IDCount = ' + #IDCount
  print #sql --find reason in the sql statement
EXEC(#sql)
END
I suggest to use sp_executesql and CAST int to nvarchar before executing query and QUOTENAME the #tablename.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spTMSA_Test_Run]
#TableName nvarchar(200),
#Parent int,
#Name nvarchar(100),
#KPI nvarchar(max),
#IDCount int
AS
BEGIN
DECLARE #sql nvarchar(max)
SELECT #sql = '
UPDATE ' + QUOTENAME(#TableName) + '
SET Parent = ' + CAST(#Parent as nvarchar(10))+ ',
Name = ''' + #Name + ''',
KPI = ''' + #KPI + '''
WHERE IDCount = ' + CAST(#IDCount as nvarchar(10)) + ';'
EXEC sp_executesql #sql
END

Dynamic T-SQL stored procedure to insert in differents tables

What is the best way to achieve this
INSERT INTO #TableName (#ColumnNames)
EXEC sp_executesql #SQLResult;
Where #TableName, #ColumnNames, #SQLResult are varchar variables
I am trying to avoid do a separate insert for each table.
The best way is to write (or generate) all reqiured procedures for all table. 23 tables times 4 procedures (insert, update, delete and select) that can be generated automatically is nothing in dev time and pain compared to the so called "generic solution".
It's a path to poor perfomance, unreadable code, sql injection hazard and countless debuging hours.
First of all I appreciate all your comments. And I agree that SQL dynamic is a pain to debug (Thanks God, management studio has this possibility). And, of course there are hundreds of different solutions
I solved it in this way finally, more or less I try to explain why this solution of SQL dynamic. The client uses xlsx spreadsheets to enter certain data, so I read the spreadsheets and I insert the (data depends on the spreadsheet to insert into the proper table). Later the data in the tables are exported to XML to send a third party sofware.
SET #SEL = N'';
DECLARE sel_cursor CURSOR
FOR (SELECT sc.name as field
FROM sys.objects so INNER JOIN sys.columns sc ON so.[object_id]=sc.[object_id]
WHERE so.name= #TableName and sc.name not in ('InitDate', 'EndDate', 'Version', 'Status'));
SET #SEL = ''; set #i = 0;
OPEN sel_cursor
FETCH NEXT FROM sel_cursor INTO #field
WHILE ##FETCH_STATUS = 0
BEGIN
set #sel = #sel + ', '+ #field
set #i = 1;
FETCH NEXT FROM sel_cursor INTO #field
END
CLOSE sel_cursor;
DEALLOCATE sel_cursor;
SET #SQL = N''
SET #SQL = #SQL + N'SELECT * INTO XLImport FROM OPENROWSET'
SET #SQL = #SQL + N'('
SET #SQL = #SQL + N'''Microsoft.ACE.OLEDB.12.0'''+','
SET #SQL = #SQL + N'''Excel 12.0 Xml; HDR=YES;'
SET #SQL = #SQL + N'Database='+#file +''''+ ','
SET #SQL = #SQL + N'''select * from ['+ #SheetName + '$]'''+');'
EXEC sp_executesql #SQL
SET #SQL = N'';
SET #SQL = #SQL + N'
SELECT '+''''+CAST(#initDate AS VARCHAR(10))+'''' +', '+ ''''+CAST(#endDate AS VARCHAR(10))+''''
+ ', '+ CAST(#version AS VARCHAR(2)) +', ' +''''+#status+''''
+ #SEL
+' FROM DBO.XLImport '
DECLARE cols_cursor CURSOR
FOR (Select COLUMN_NAME From INFORMATION_SCHEMA.COLUMNS where table_name = #tableName);
SET #SEL = ''; set #i = 0;
OPEN cols_cursor
FETCH NEXT FROM cols_cursor INTO #field
WHILE ##FETCH_STATUS = 0
BEGIN
set #sel = #sel + #field + ', '
set #i = 1;
FETCH NEXT FROM cols_cursor INTO #field
END
CLOSE cols_cursor;
DEALLOCATE cols_cursor;
SET #SEL = LEFT(#SEL, LEN(#SEL) - 1) -- remove last ,
SET #SQL = N''
SET #SQL = #SQL + N'SELECT * INTO XLImport FROM OPENROWSET'
SET #SQL = #SQL + N'('
SET #SQL = #SQL + N'''Microsoft.ACE.OLEDB.12.0'''+','
SET #SQL = #SQL + N'''Excel 12.0 Xml; HDR=YES;'
SET #SQL = #SQL + N'Database='+#file +''''+ ','
SET #SQL = #SQL + N'''select * from ['+ #SheetName + '$]'''+');'
EXEC sp_executesql #SQL
SET #SQLString =
N'INSERT INTO '+ #TableName + '('+ #SEL +') ' + #SQL;
EXEC sp_executesql #SQLString
Use EXECUTE sp_executesql #sql, here is example:
create proc sp_DynamicExcuteStore
#TableName varchar(50),
#ColumnNames varchar(50),
#SQLResult varchar(max)
as
declare #sql nvarchar(max) = '
INSERT INTO '+#TableName+' ('+#ColumnNames+')
EXEC sp_executesql '+#SQLResult
EXECUTE sp_executesql #sql
go
create proc sp_test
as
select 'test' + convert(varchar,RAND())
go
CREATE TABLE [dbo].[Test](
[text1] [nvarchar](500) NULL
) ON [PRIMARY]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[sp_DynamicExcuteStore]
#TableName = N'Test',
#ColumnNames = N'text1',
#SQLResult = N'proc_test'
SELECT 'Return Value' = #return_value
GO
SELECT TOP 1000 [text1]
FROM [test].[dbo].[Test]

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