how to backup with a unique file name - sql-server

i am trying to take a backup by creating a job in sql server agent using stored procedure. i am able to take the backup but each time it overwrites my previous backup file. i want my backup should create a different file with unique file name using date. how can I achieve this. below is my code, any help would be appreciated
DECLARE #backupfilename VARCHAR(1000)
DECLARE #path VARCHAR(1000)
SET #backupfilename='C:\SqlBackups\AdventureWorks\Full\backup_' + CONVERT (VarChar, GetDate(), 112) + '.bak'
SET #path = 'BACKUP DATABASE AdventureWorks2012 TO DISK = ''' + #backupfilename + ''''
EXEC msdb.dbo.sp_add_jobstep
#job_name = 'BackupDatabase',
#step_name = 'Weekly Full Backup',
#subsystem = 'TSQL',
#command = #path;

Related

MSSQL Script to export entire database

It's possible create a script (to launch from a stored procedure) that export the entire database (schema + data) into a .sql file?
I need this to make a backup from a MSSQL 2019 and I need to restore to MSSQL 2017... Using Tasks->Generate Scripts from SSMS it's possible do what I need, but I wish schedule this and the best way I think is made a script to launch from a stored procedure.
Thanks in advance!
Here is the script that will allow you to backup each database within your instance of SQL Server
DECLARE #name NVARCHAR(256) -- database name
DECLARE #path NVARCHAR(512) -- path for backup files
DECLARE #fileName NVARCHAR(512) -- filename for backup
DECLARE #fileDate NVARCHAR(40) -- used for file name
-- specify database backup directory
SET #path = 'C:\test\'
-- specify filename format
SELECT #fileDate = CONVERT(NVARCHAR(20),GETDATE(),112)
DECLARE db_cursor CURSOR READ_ONLY FOR
SELECT name
FROM master.sys.databases
WHERE name = #name
AND state = 0 -- database is online
AND is_in_standby = 0 -- database is not read only for log shipping
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
SET #fileName = #path + #name + '_' + #fileDate + '.sql'
BACKUP DATABASE #name TO DISK = #fileName
FETCH NEXT FROM db_cursor INTO #name
END
CLOSE db_cursor
DEALLOCATE db_cursor
You have to change the #path to the appropriate backup directory.
NOTE: Make sure that you have read and write access to the DB

How to backup all databases on SQL Server 2008

I have been working on SQL Server 2008 R2 for 4 years and it's time to format my laptop.
I just use the default instance, which I can access using the . as server name, and then my username and password for user authentication.
Now I want to format my laptop, and it is almost impossible to backup manually all the database.
I found in the following path
C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL
all the databases that I have, for each database I found:
databasename_log.ldf
databasename.mdf
I copied these files to an external hard drive.
My question:
Are those files enough to import the database after formatting? Will they work if I installed (after formatting) SQL Server 2012 not 2008 R2?
I found the SQL from this article useful in taking backups of all databases on a server.
DECLARE #name VARCHAR(50) -- database name
DECLARE #path VARCHAR(256) -- path for backup files
DECLARE #fileName VARCHAR(256) -- filename for backup
DECLARE #fileDate VARCHAR(20) -- used for file name
-- specify database backup directory
SET #path = 'C:\Backup\'
-- specify filename format
SELECT #fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb') -- exclude these databases
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
SET #fileName = #path + #name + '_' + #fileDate + '.BAK'
BACKUP DATABASE #name TO DISK = #fileName
FETCH NEXT FROM db_cursor INTO #name
END
CLOSE db_cursor
DEALLOCATE db_cursor
You can use SELECT Statement or CURSOR like this:
DECLARE #PathForBackUp VARCHAR(255)
SET #PathForBackUp = 'F:\Backup\User DB\'
SELECT 'BACKUP DATABASE [' + name + '] TO DISK = N''' + #PathForBackUp + '' + name + '.bak''
WITH NOFORMAT, NOINIT, NAME = N''' + name + '_FullBackUp'', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 5'
FROM sys.databases
WHERE database_id > 4
OR
DECLARE #DBName VARCHAR(255)
DECLARE #PathForBackUp VARCHAR(255)
DECLARE #FileName VARCHAR(255)
DECLARE #DateFile VARCHAR(255)
DECLARE #SQL NVARCHAR(2048)
SET #PathForBackUp = 'F:\Backup\User DB\'
SET #DateFile = REPLACE(REPLACE(CONVERT(VARCHAR(20),GETDATE(),120) ,' ','T'), ':','')
DECLARE BACKUPING CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases WHERE dbid > 4
OPEN BACKUPING
FETCH NEXT FROM BACKUPING INTO #DBName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #FileName = #PathForBackUp + #DBName + '_' + #DateFile + '.BAK'
SET #SQL = 'BACKUP DATABASE '+#DBName+ ' TO DISK = '''+#FileName+''' WITH COMPRESSION '
PRINT #SQL
EXECUTE sp_executesql #sql
FETCH NEXT FROM BACKUPING INTO #DBName
END
CLOSE BACKUPING
DEALLOCATE BACKUPING
If you want to more about these solution I wrote post about that here:
http://www.pigeonsql.com/single-post/2016/12/20/Backup-All-Users-databases-via-Select-and-Cursor
Are those files enough to import the database after formatting? Will they work if I installed (after formatting) SQL Server 2012 not 2008 R2?
You are taking file level backup of database mdf and ldf file this is bit different from T-SQL backup. As I can read you have already formatted your machine and you have not taken backup so in that case please copy the mdf and ldf file on the local drive and then attach those files to create the database.
Please note before attaching make sure you have installed Service pack(SP), if it was installed on SQL Server 2008 r2 before formatting. If not please install SP after attaching database.
To attach database you can use both TSQL and GUI. Below link would help you in attaching the data files. Before opening SSMS please right click on SSMS and select run as administrator to avoid any access denied message.
Attach a database using SSMS
Sample script for attach
CREATE DATABASE DatabaseName
ON (FILENAME = 'FilePath\FileName.mdf'), -- Main Data File .mdf
(FILENAME = 'FilePath\LogFileName.ldf'), -- Log file .ldf
(FILENAME = 'FilePath\SecondaryDataFile.ndf) -- Optional - any secondary data files
FOR ATTACH
GO

Backup failed in stored procedure

If I am using BACKUP statement:
BACKUP DATABASE [Database name]
TO DISK = ‘Location’
WITH INIT, NOSKIP, NOFORMAT
Backup did work. But if I am trying to use same query in a stored procedure like
SET #SQLCMD = N'BACKUP DATABASE [Database Name] TO DISK = ''' + #FILENAME + ''' WITH INIT,NOSKIP, NOFORMAT'
EXEC (#SQLCMD)
I am getting error message:
Msg 203, Level 16, State 2, Procedure sp_BackupDatabase, Line 31
The name 'BACKUP DATABASE [Database Name] TO DISK =
'C:\Users\PC\Desktop\Backup\20121008\db.bak' WITH INIT,NOSKIP,
NOFORMAT' is not a valid identifier.
I couldn't figure out where I am making error.
Sir what you are doing executes the command as a stored procedure and ofcourse it's not a valid identifier for the name of the stored procedure! So I recommend you to use "sp_executesql" instead. If your code works fine, it should work everywhere else.
Referring to http://msdn.microsoft.com/en-us/library/ms175170(v=sql.105).aspx
Like this code:
Declare #Command Nvarchar(500);
Select #Command = N'BACKUP DATABASE [Database Name] TO DISK = ''' + #FILENAME + ''' WITH INIT,NOSKIP, NOFORMAT';
Execute sp_executesql #Command
Cheers

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

I have an MS SQL Server 2008 Express system which contains a database that I would like to 'copy and rename' (for testing purposes) but I am unaware of a simple way to achieve this.
I notice that in the R2 version of SQL Server there is a copy database wizard, but sadly I can't upgrade.
The database in question is around a gig.
I attempted to restore a backup of the database I want to copy into a new database, but with no luck.
Install Microsoft SQL Management Studio, which you can download for free from Microsoft's website:
Version 2008
Microsoft SQL Management Studio 2008 is part of SQL Server 2008 Express with Advanced Services
Version 2012
Click download button and check ENU\x64\SQLManagementStudio_x64_ENU.exe
Version 2014
Click download button and check MgmtStudio 64BIT\SQLManagementStudio_x64_ENU.exe
Open Microsoft SQL Management Studio.
Backup original database to .BAK file (db -> Task -> Backup).
Create empty database with new name (clone). Note comments below as this is optional.
Click to clone database and open restore dialog (see image)
Select Device and add the backup file from step 3.
Change destination to test database
Change location of database files, it must be different from the original. You can type directly into text box, just add postfix. (NOTE: Order is important. Select checkbox, then change the filenames.)
Check WITH REPLACE and WITH KEEP_REPLICATION
Right-click the database to clone, click Tasks, click Copy Database.... Follow the wizard and you're done.
You could try to detach the database, copy the files to new names at a command prompt, then attach both DBs.
In SQL:
USE master;
GO
EXEC sp_detach_db
#dbname = N'OriginalDB';
GO
At Command prompt (I've simplified the file paths for the sake of this example):
copy c:\OriginalDB.mdf c:\NewDB.mdf
copy c:\OriginalDB.ldf c:\NewDB.ldf
In SQL again:
USE master;
GO
CREATE DATABASE OriginalDB
ON (FILENAME = 'C:\OriginalDB.mdf'),
(FILENAME = 'C:\OriginalDB.ldf')
FOR ATTACH;
GO
CREATE DATABASE NewDB
ON (FILENAME = 'C:\NewDB.mdf'),
(FILENAME = 'C:\NewDB.ldf')
FOR ATTACH;
GO
It turns out that I had attempted to restore from a backup incorrectly.
Initially I created a new database and then attempted to restore the backup here.
What I should have done, and what worked in the end, was to bring up the restore dialog and type the name of the new database in the destination field.
So, in short, restoring from a backup did the trick.
Thanks for all the feedback and suggestions guys
This is the script I use. A bit tricky but it works. Tested on SQL Server 2012.
DECLARE #backupPath nvarchar(400);
DECLARE #sourceDb nvarchar(50);
DECLARE #sourceDb_log nvarchar(50);
DECLARE #destDb nvarchar(50);
DECLARE #destMdf nvarchar(100);
DECLARE #destLdf nvarchar(100);
DECLARE #sqlServerDbFolder nvarchar(100);
SET #sourceDb = 'db1'
SET #sourceDb_log = #sourceDb + '_log'
SET #backupPath = 'E:\DB SQL\MSSQL11.MSSQLSERVER\MSSQL\Backup\' + #sourceDb + '.bak' --ATTENTION: file must already exist and SQL Server must have access to it
SET #sqlServerDbFolder = 'E:\DB SQL\MSSQL11.MSSQLSERVER\MSSQL\DATA\'
SET #destDb = 'db2'
SET #destMdf = #sqlServerDbFolder + #destDb + '.mdf'
SET #destLdf = #sqlServerDbFolder + #destDb + '_log' + '.ldf'
BACKUP DATABASE #sourceDb TO DISK = #backupPath
RESTORE DATABASE #destDb FROM DISK = #backupPath
WITH REPLACE,
MOVE #sourceDb TO #destMdf,
MOVE #sourceDb_log TO #destLdf
None of the solutions mentioned here worked for me - I am using SQL Server Management Studio 2014.
Instead I had to uncheck the "Take tail-log backup before restore" checkbox in the "Options" screen: in my version it is checked by default and prevents the Restore operation to be completed.
After unchecking it, the Restore operation proceeded without issues.
From SSMS :
1 - Backup original database to .BAK file (your_source_db -> Task -> Backup).
2 - Right clicking the "Databases" and 'Restore Database'
3 - Device > ... (button) > Add > select the your_source_db.bak
4 - In 'General' tab, in 'Destination' section, rename in 'Database' your_source_db to new_name_db
5 - In 'Files' tab, tick 'Relocate all files to folder',
Rename in 'Restore As' column the two lignes to keep consistency with new_name_db (.mdf, _log.ldf)
6 - In 'Options' tab, in 'Restore options' section, tick two fist options ('Overwrite...', 'Preserve...') and for 'Recovery state' : 'RESTORE WITH RECOVERY'
Make also sure that in 'Tail-Log backup' section options are unticked to avoid keeping source db in 'restoring state' !
Using MS SQL Server 2012, you need to perform 3 basic steps:
First, generate .sql file containing only the structure of the source DB
right click on the source DB and then Tasks then Generate Scripts
follow the wizard and save the .sql file locally
Second, replace the source DB with the destination one in the .sql file
Right click on the destination file, select New Query and Ctrl-H or (Edit - Find and replace - Quick replace)
Finally, populate with data
Right click on the destination DB, then select Tasks and Import Data
Data source drop down set to ".net framework data provider for SQL server" + set the connection string text field under DATA ex: Data Source=Mehdi\SQLEXPRESS;Initial Catalog=db_test;User ID=sa;Password=sqlrpwrd15
do the same with the destination
check the table you want to transfer or check box besides "source: ..." to check all of them
You are done.
If the database is not very large, you might look at the 'Script Database' commands in SQL Server Management Studio Express, which are in a context menu off the database item itself in the explorer.
You can choose what all to script; you want the objects and the data, of course. You will then save the entire script to a single file. Then you can use that file to re-create the database; just make sure the USE command at the top is set to the proper database.
In SQL Server 2008 R2, back-up the database as a file into a folder.
Then chose the restore option that appears in the "Database" folder.
In the wizard enter the new name that you want in the target database.
And choose restore frrom file and use the file you just created.
I jsut did it and it was very fast (my DB was small, but still)
Pablo.
The solution, based on this comment: https://stackoverflow.com/a/22409447/2399045 .
Just set settings: DB name, temp folder, db files folder.
And after run you will have the copy of DB with Name in "sourceDBName_yyyy-mm-dd" format.
-- Settings --
-- New DB name will have name = sourceDB_yyyy-mm-dd
declare #sourceDbName nvarchar(50) = 'MyDbName';
declare #tmpFolder nvarchar(50) = 'C:\Temp\'
declare #sqlServerDbFolder nvarchar(100) = 'C:\Databases\'
-- Execution --
declare #sourceDbFile nvarchar(50);
declare #sourceDbFileLog nvarchar(50);
declare #destinationDbName nvarchar(50) = #sourceDbName + '_' + (select convert(varchar(10),getdate(), 121))
declare #backupPath nvarchar(400) = #tmpFolder + #destinationDbName + '.bak'
declare #destMdf nvarchar(100) = #sqlServerDbFolder + #destinationDbName + '.mdf'
declare #destLdf nvarchar(100) = #sqlServerDbFolder + #destinationDbName + '_log' + '.ldf'
SET #sourceDbFile = (SELECT top 1 files.name
FROM sys.databases dbs
INNER JOIN sys.master_files files
ON dbs.database_id = files.database_id
WHERE dbs.name = #sourceDbName
AND files.[type] = 0)
SET #sourceDbFileLog = (SELECT top 1 files.name
FROM sys.databases dbs
INNER JOIN sys.master_files files
ON dbs.database_id = files.database_id
WHERE dbs.name = #sourceDbName
AND files.[type] = 1)
BACKUP DATABASE #sourceDbName TO DISK = #backupPath
RESTORE DATABASE #destinationDbName FROM DISK = #backupPath
WITH REPLACE,
MOVE #sourceDbFile TO #destMdf,
MOVE #sourceDbFileLog TO #destLdf
Another way that does the trick by using import/export wizard, first create an empty database, then choose the source which is your server with the source database, and then in the destination choose the same server with the destination database (using the empty database you created at first), then hit finish
It will create all tables and transfer all the data into the new database,
Script based on Joe answer (detach, copy files, attach both).
Run Managment Studio as Administrator account.
It's not necessary, but maybe access denied error on executing.
Configure sql server for execute xp_cmdshel
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
Run script, but type your db names in #dbName and #copyDBName variables before.
USE master;
GO
DECLARE #dbName NVARCHAR(255) = 'Products'
DECLARE #copyDBName NVARCHAR(255) = 'Products_branch'
-- get DB files
CREATE TABLE ##DBFileNames([FileName] NVARCHAR(255))
EXEC('
INSERT INTO ##DBFileNames([FileName])
SELECT [filename] FROM ' + #dbName + '.sys.sysfiles')
-- drop connections
EXEC('ALTER DATABASE ' + #dbName + ' SET OFFLINE WITH ROLLBACK IMMEDIATE')
EXEC('ALTER DATABASE ' + #dbName + ' SET SINGLE_USER')
-- detach
EXEC('EXEC sp_detach_db #dbname = ''' + #dbName + '''')
-- copy files
DECLARE #filename NVARCHAR(255), #path NVARCHAR(255), #ext NVARCHAR(255), #copyFileName NVARCHAR(255), #command NVARCHAR(MAX) = ''
DECLARE
#oldAttachCommand NVARCHAR(MAX) =
'CREATE DATABASE ' + #dbName + ' ON ',
#newAttachCommand NVARCHAR(MAX) =
'CREATE DATABASE ' + #copyDBName + ' ON '
DECLARE curs CURSOR FOR
SELECT [filename] FROM ##DBFileNames
OPEN curs
FETCH NEXT FROM curs INTO #filename
WHILE ##FETCH_STATUS = 0
BEGIN
SET #path = REVERSE(RIGHT(REVERSE(#filename),(LEN(#filename)-CHARINDEX('\', REVERSE(#filename),1))+1))
SET #ext = RIGHT(#filename,4)
SET #copyFileName = #path + #copyDBName + #ext
SET #command = 'EXEC master..xp_cmdshell ''COPY "' + #filename + '" "' + #copyFileName + '"'''
PRINT #command
EXEC(#command);
SET #oldAttachCommand = #oldAttachCommand + '(FILENAME = "' + #filename + '"),'
SET #newAttachCommand = #newAttachCommand + '(FILENAME = "' + #copyFileName + '"),'
FETCH NEXT FROM curs INTO #filename
END
CLOSE curs
DEALLOCATE curs
-- attach
SET #oldAttachCommand = LEFT(#oldAttachCommand, LEN(#oldAttachCommand) - 1) + ' FOR ATTACH'
SET #newAttachCommand = LEFT(#newAttachCommand, LEN(#newAttachCommand) - 1) + ' FOR ATTACH'
-- attach old db
PRINT #oldAttachCommand
EXEC(#oldAttachCommand)
-- attach copy db
PRINT #newAttachCommand
EXEC(#newAttachCommand)
DROP TABLE ##DBFileNames
You could just create a new database and then go to tasks, import data, and import all the data from the database you want to duplicate to the database you just created.
This program copies a database to the same server under a different name. I relied on examples given on this site with some improvements.
-- Copies a database to the same server
-- Copying the database is based on backing up the original database and restoring with a different name
DECLARE #sourceDb nvarchar(50);
DECLARE #destDb nvarchar(50);
DECLARE #backupTempDir nvarchar(200)
SET #sourceDb = N'Northwind' -- The name of the source database
SET #destDb = N'Northwind_copy' -- The name of the target database
SET #backupTempDir = N'c:\temp' -- The name of the temporary directory in which the temporary backup file will be saved
-- --------- ---
DECLARE #sourceDb_ROWS nvarchar(50);
DECLARE #sourceDb_LOG nvarchar(50);
DECLARE #backupPath nvarchar(400);
DECLARE #destMdf nvarchar(100);
DECLARE #destLdf nvarchar(100);
DECLARE #sqlServerDbFolder nvarchar(100);
Declare #Ret as int = -1
Declare #RetDescription nvarchar(200) = ''
-- Temporary backup file name
SET #backupPath = #backupTempDir+ '\TempDb_' + #sourceDb + '.bak'
-- Finds the physical location of the files on the disk
set #sqlServerDbFolder = (SELECT top(1) physical_name as dir
FROM sys.master_files where DB_NAME(database_id) = #sourceDb );
-- Clears the file name and leaves the directory name
set #sqlServerDbFolder = REVERSE(SUBSTRING(REVERSE(#sqlServerDbFolder), CHARINDEX('\', REVERSE(#sqlServerDbFolder)) + 1, LEN(#sqlServerDbFolder))) + '\'
-- Finds the logical name for the .mdf file
set #sourceDb_ROWS = (SELECT f.name LogicalName FROM sys.master_files f INNER JOIN sys.databases d ON d.database_id = f.database_id
where d.name = #sourceDb and f.type_desc = 'ROWS' )
-- Finds the logical name for the .ldf file
set #sourceDb_LOG = (SELECT f.name LogicalName FROM sys.master_files f INNER JOIN sys.databases d ON d.database_id = f.database_id
where d.name = #sourceDb and f.type_desc = 'LOG' )
-- Composes the names of the physical files for the new database
SET #destMdf = #sqlServerDbFolder + #destDb + N'.mdf'
SET #destLdf = #sqlServerDbFolder + #destDb + N'_log' + N'.ldf'
-- If the source name is the same as the target name does not perform the operation
if #sourceDb <> #destDb
begin
-- Checks if the target database already exists
IF Not EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = #destDb)
begin
-- Checks if the source database exists
IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = #sourceDb) and (#sqlServerDbFolder is not null)
begin
-- Opens the permission to run xp_cmdshell
EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE WITH OVERRIDE
-- If the temporary backup directory does not exist it creates it
declare #md as nvarchar(100) = N'if not exist ' + #backupTempDir + N' md ' +#backupTempDir
exec xp_cmdshell #md, no_output
-- Creates a backup to the source database to the temporary file
BACKUP DATABASE #sourceDb TO DISK = #backupPath
-- Restores the database with a new name
RESTORE DATABASE #destDb FROM DISK = #backupPath
WITH REPLACE,
MOVE #sourceDb_ROWS TO #destMdf,
MOVE #sourceDb_LOG TO #destLdf
-- Deletes the temporary backup file
declare #del as varchar(100) = 'if exist ' + #backupPath +' del ' +#backupPath
exec xp_cmdshell #del , no_output
-- Close the permission to run xp_cmdshell
EXEC master.dbo.sp_configure 'xp_cmdshell', 0
RECONFIGURE WITH OVERRIDE
EXEC master.dbo.sp_configure 'show advanced options', 0
RECONFIGURE WITH OVERRIDE
set #ret = 1
set #RetDescription = 'The ' +#sourceDb + ' database was successfully copied to ' + #destDb
end
else
begin
set #RetDescription = 'The source database '''+ #sourceDb + ''' is not exists.'
set #ret = -3
end
end
else
begin
set #RetDescription = 'The target database '''+ #destDb + ''' already exists.'
set #ret = -4
end
end
else
begin
set #RetDescription = 'The target database ''' +#destDb + ''' and the source database '''+ #sourceDb + ''' have the same name.'
set #ret = -5
end
select #ret as Ret, #RetDescription as RetDescription
<!doctype html>
<head>
<title>Copy Database</title>
</head>
<body>
<?php
$servername = "localhost:xxxx";
$user1 = "user1";
$pw1 = "pw1";
$db1 = "db1";
$conn1 = new mysqli($servername,$user1,$pw1,$db1);
if($conn1->connect_error) {
die("Conn1 failed: " . $conn1->connect_error);
}
$user2 = "user2";
$pw2 = "pw2";
$db2 = "db2";
$conn2 = new mysqli($servername,$user2,$pw2,$db2);
if($conn2->connect_error) {
die("Conn2 failed: " . $conn2->connect_error);
}
$sqlDB1 = "SELECT * FROM table1";
$resultDB1 = $conn1->query($sqlDB1);
if($resultDB1->num_rows > 0) {
while($row = $resultDB1->fetch_assoc()) {
$sqlDB2 = "INSERT INTO table2 (col1, col2) VALUES ('" . $row["tableRow1"] . "','" . $row["tableRow2"] . "')";
$resultDB2 = $conn2->query($sqlDB2);
}
}else{
echo "0 results";
}
$conn1->close();
$conn2->close();
?>
</body>
If you are MS SQL 2014 and newer;
DBCC CLONEDATABASE (CurrentDBName, NewDBName)
GO
Details;

What is the proper way to move a database from one drive to another in SQL Server 2005?

I'm not looking to relocate the database to another server entirely, but just move the data file(s) and log file to another drive with more space. I've seen conflicting directions on how to do this, so I'm looking for the recommended proper way of doing it.
Detach the Database:
use master
go
sp_detach_db 'mydb'
Move the Database files (Xcopy through xp_cmdshell shown):
DECLARE #SRCData nvarchar(1000)
SET #SRCData = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\mydb.mdf';
DECLARE #SRCLog nvarchar(1000)
SET #SRCLog = N'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\mydb_log.ldf';
DECLARE #FILEPATH nvarchar(1000);
DECLARE #LOGPATH nvarchar(1000);
SET #FILEPATH = N'xcopy /Y ' + #SRCData + N' D:\Data';
SET #LOGPATH = N'xcopy /Y ' + #SRCLog + N' E:\Log';
exec xp_cmdshell #FILEPATH;
exec xp_cmdshell #LOGPATH;
ReAttach Database:
sp_attach_db 'mydb', 'D:\Data\mydb.mdf', 'E:\Log\mydb_log.ldf'
There's more detail at this Microsoft KB article.
Another way - detach database files (database->tasks->detach), move them to new drive and then attach again.
But way described by Jay S is the simpliest.
To be absolutely safe, I would do the following:
Backup the database to a BAK file.
Take the current database offline, or delete it if you want to.
Restore the database and change the location of the MDF and LDF files.
Scripts sample:
-- Get the file list from a backup file.
-- This will show you current logical names and paths in the BAK file
RESTORE FILELISTONLY FROM disk = N'C:\Backups\MyDatabaseName.bak'
-- Perform the restore of the database from the backup file.
-- Replace 'move' names (MDFLogicalName, LDFLogicalName) with those found in
-- the previous filelistonly command
restore database MyDatabaseName
from disk = N'C:\Backups\MyDatabaseName.bak'
with move 'MDFLogicalName' to 'D:\SQLData\MyDatabaseName.mdf',
move 'LDFLogicalName' to 'D:\SQLLogs\MyDatabaseName_log.ldf',
replace, stats=10;
Notes
The first script will get you the current names and paths that you'll need in the second script. The second script restores the database back to the name you want it to have, but you can change where you want to store. In the example above, it moves the MDF and LDF files to the D: drive.
I'd rather not enable xp_cmdshell on my SQL Server instance, so I wrote a function to do this using Powershell instead; it was especially useful when I had to move a large number of databases.
function Move-Database
{
param ($database, $newPath)
$paths = Invoke-SqlCmd "SELECT master_files.physical_name as Path
FROM sys.databases
JOIN sys.master_files ON master_files.database_id = databases.database_id
WHERE databases.name = '$database';";
$paths = $paths | % { $_.Path };
if (!$paths)
{
throw "Unknown database '$database'";
}
Write-Host "Setting $database to single-user mode...";
Invoke-SqlCmd "ALTER DATABASE [$database] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;";
Write-Host "Detaching $database";
Invoke-SqlCmd "EXEC sp_detach_db '$database';";
if (!(test-path $newPath))
{
[void](mkdir $newPath);
}
$clauses = #();
foreach ($oldFile in $paths)
{
$filename = [System.IO.Path]::GetFileName($oldFile);
$newFile = [System.IO.Path]::Combine($newPath, $filename);
$clauses += "(FILENAME = `"$newFile`")";
Write-Host "Moving $oldFile to $newFile";
mv $oldFile $newFile;
}
$clauses = $clauses -join ", ";
Write-Host "Re-attaching $database";
Invoke-SqlCmd "CREATE DATABASE [$database] ON $clauses FOR ATTACH;";
Write-Host "All done!";
}
You can use it like so:
Move-Database -database "MyDatabase" -newPath "D:\SqlData";
I also think this method is a bit more robust than the others - what if your database is split into many files or you have a strange naming convention for logs for example?
I needed to move multiple databases within same server, so I expanded the accepted solution a bit, to avoid copying and pasting or retyping commands. This allows moving data files in one script run, only changing the database name. Note this assumes that advanced commands are enabled; if not, use sp_configure. The data and log files are assumed to be in the same directory.
use master
DECLARE #DBName nvarchar(50)
SET #DBName = 'YOUR_DB_NAME'
DECLARE #RC int
EXEC #RC = sp_detach_db #DBName
DECLARE #NewPath nvarchar(1000)
SET #NewPath = 'E:\Data\Microsoft SQL Server\Data\';
DECLARE #OldPath nvarchar(1000)
SET #OldPath = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\';
DECLARE #DBFileName nvarchar(100)
SET #DBFileName = #DBName + '.mdf';
DECLARE #LogFileName nvarchar(100)
SET #LogFileName = #DBName + '_log.ldf';
DECLARE #SRCData nvarchar(1000)
SET #SRCData = #OldPath + #DBFileName;
DECLARE #SRCLog nvarchar(1000)
SET #SRCLog = #OldPath + #LogFileName;
DECLARE #DESTData nvarchar(1000)
SET #DESTData = #NewPath + #DBFileName;
DECLARE #DESTLog nvarchar(1000)
SET #DESTLog = #NewPath + #LogFileName;
DECLARE #FILEPATH nvarchar(1000);
DECLARE #LOGPATH nvarchar(1000);
SET #FILEPATH = N'xcopy /Y "' + #SRCData + N'" "' + #NewPath + '"';
SET #LOGPATH = N'xcopy /Y "' + #SRCLog + N'" "' + #NewPath + '"';
exec xp_cmdshell #FILEPATH;
exec xp_cmdshell #LOGPATH;
EXEC #RC = sp_attach_db #DBName, #DESTData, #DESTLog
go
You also need to make sure the user under which the SQL Server process is running has access to the folder. For SQL2014, the default user process is "NT Service\MSSQL$SQL2014".

Resources