How To Create all database backup in single query - sql

How can i create backup file for their all database which are available on their SQL Server instance.

If anyone wants to create backup file for their all database which are available on their SQL Server instance, you can use this stored procedure.
You have to create this stored procedure somewhere and give your path where you want to stored all .bak file
-- Use code for creating all database backup
USE [master]
GO
CREATE PROCEDURE [dbo].[CreateDBBackup] --create this sp somewhere in your SQL Server
AS
BEGIN
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 location
SET #path = 'D:\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')
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #name
WHILE ##FETCH_STATUS = 0
BEGIN
SET #fileName = #path + #name + '.BAK'
BACKUP DATABASE #name TO DISK = #fileName
FETCH NEXT FROM db_cursor INTO #name
END
CLOSE db_cursor
DEALLOCATE db_cursor
END

Related

How do I backup a database with a stored procedure in SQL?

I'm trying to create a stored procedure that backs up a database, however whenever I execute it, the folder I'm trying to backup to remains empty.
Here is my stored procedure:
USE [HarvestMan_SoutheskFarm_03_05_22]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Will Sewell
-- Create date: 03-05-2022
-- Description: Procedure to back up a database
-- =============================================
ALTER PROCEDURE [dbo].[BackupDatabases]
#name VARCHAR(MAX) = 'HarvestMan_SoutheskFarm_03_05_22' -- DB NAME TO CREATE BACKUP
AS
BEGIN
DECLARE #path VARCHAR(256) -- path of backup files
DECLARE #fileName VARCHAR(256) -- filename for backup
DECLARE #fileDate VARCHAR(20) -- used for file name
SET #path = 'C:\Users\will.sewell\Documents\Database_Test'
-- specify filename format
SELECT #fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
BEGIN
SET #fileName = #path + #name + '_' + #fileDate + '.BAK'
BACKUP DATABASE #name TO DISK = #fileName
END
END
I have tried changing the drive that it is writing to.
I've copy and pasted the database name I want to backup to ensure no spelling mistakes.
I'm assuming it might be a permissions issue or a visible files in the folder.
When I execute the stored procedure, I get this:
Processed 24472 pages for database 'HarvestMan_SoutheskFarm_03_05_22', file 'HarvestMan_dat' on file 2.
Processed 1 pages for database 'HarvestMan_SoutheskFarm_03_05_22', file 'HarvestMan_log' on file 2. BACKUP DATABASE successfully processed 24473 pages in 5.039 seconds (37.941 MB/sec).
Completion time: 2022-05-04T10:27:30.2344290+01:00
Dear you have to create the stored procedure first
also your path missing the last slash
BIG Note you must define an actual path
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[BackupDatabases]
#name VARCHAR(MAX) = 'ActualDataBaseName' -- DB NAME TO CREATE BACKUP
AS
BEGIN
DECLARE #path VARCHAR(256) -- path of backup files
DECLARE #fileName VARCHAR(256) -- filename for backup
DECLARE #fileDate VARCHAR(20) -- used for file name
SET #path = 'C:\ActualPath\'
-- specify filename format
SELECT #fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
BEGIN
SET #fileName = #path + #name + '_' + #fileDate + '.BAK'
BACKUP DATABASE #name TO DISK = #fileName
END
END

Iterate through each of the values in one SQL table to find the associated records in another table

In SQL, I need to return a set of records from one table based on each value of a field in a Lookup table. So I have a lookup table that contains a filename field and I need to iterate through each of the filenames and find the records in another table based on this field (filename is the keyfield in both tables). After I identify each set of records, I need to then save each of them as a CSV file locally on my computer. I tried the below cursor and it's not working. Can someone assist?
DECLARE #name VARCHAR(50) -- database name
DECLARE #path VARCHAR(256) -- path to save file
DECLARE #fileName VARCHAR(256) -- filename for output file DECLARE #fileDate VARCHAR(20) -- used for file name
SET #path = 'C:\Output\'
SELECT #fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
DECLARE db_cursor CURSOR FOR
SELECT * FROM dbo.filenamelookup fl JOIN dbo.recordstable rt ON fl.filename = rt.filename OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #temp
WHILE ##FETCH_STATUS = 0
BEGIN
SET #fileName = #path + #name + '_' + #fileDate + '.csv'
BACKUP DATABASE #temp TO DISK = #fileName
FETCH NEXT FROM db_cursor INTO #name
END
CLOSE db_cursor
DEALLOCATE db_cursor
If you're using MSSQL, I would say use the BCP or SQLCMD utilities. Here is a previous post on the same issue:
https://dba.stackexchange.com/questions/23566/writing-select-result-to-a-csv-file

get sql log file name from within a script

We have a few test databases that we are throwing test indexes into and the log file gets bloated real quickly due to us dropping the contents of the table and repopulating it.
I have found, thanks to Stack Overflow, a few scripts and put them together to do what I need.
Here is the script:
USE SSSIndexes
GO
ALTER DATABASE SSSIndexes SET RECOVERY SIMPLE WITH NO_WAIT
GO
DBCC SHRINKFILE(N'SSSIndexes_Log', 1) <-- my issue is here
GO
The problem is the log file name. Is there a way to get the log file name without having to look it up manually and include it in the script to where this part is automated?
Btw, we never intend on restore this database. These are temporary indexes.
Thanks!
USE SSSIndexes
GO
ALTER DATABASE SSSIndexes SET RECOVERY SIMPLE WITH NO_WAIT
GO
DECLARE #Name NVARCHAR(50)
DECLARE cur CURSOR FOR
SELECT [name]
FROM [sys].[database_files]
where [type] = 1
OPEN cur
FETCH NEXT FROM cur INTO #Name
WHILE ##FETCH_STATUS = 0
BEGIN
DBCC SHRINKFILE(#Name, 1)
FETCH NEXT FROM cur INTO #Name
END
CLOSE cur
DEALLOCATE cur
You can use this to generate script for log file truncating of all databases on a specific server. To stick to specific databases use a filter.
SELECT
' USE [' + name + ']; GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE [' + name + '] SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DECLARE #logname varchar(128);
SELECT TOP 1 #logname=[name] FROM [' + name + '].[sys].[database_files] WHERE [type] = 1;
DBCC SHRINKFILE (#logname, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE [' + name + '] SET RECOVERY FULL;
GO
' AS qry FROM master.dbo.sysdatabases
WHERE dbid > 6
WARNING!!!: YOU SHOULD ONLY DO THIS ON TEST DB SERVERS. Production DBs typically WANT to have FULL recovery mode. Test DBs you usually don't care.
Expanding on Abdul's answer (I had trouble getting it to show in new lines) and Dis' answers this finds the first db that has recovery FULL, sets it to simple and shrinks it... just keep clicking execute until it returns null
declare #dbname nvarchar(50)
declare #logfilename nvarchar(100)
select top(1) #dbname = name from sys.databases where recovery_model_desc <> 'SIMPLE' AND name <> 'tempdb'
declare #shrinkdb nvarchar(500)
set #shrinkdb = 'USE master
ALTER DATABASE [' + #dbname + '] SET RECOVERY SIMPLE
'
select #shrinkdb
execute sp_executesql #shrinkdb
set #shrinkdb = 'USE [' + #dbname + ']
DECLARE #Name NVARCHAR(50)
DECLARE cur CURSOR FOR
SELECT [name]
FROM [sys].[database_files]
where [type] = 1
OPEN cur
FETCH NEXT FROM cur INTO #Name
WHILE ##FETCH_STATUS = 0
BEGIN
DBCC SHRINKFILE(#Name, 1)
FETCH NEXT FROM cur INTO #Name
END
CLOSE cur
DEALLOCATE cur
'
select #shrinkdb
execute sp_executesql #shrinkdb

SQL Server Backup (not restore!) error: The media set has 2 media families but only 1 are provided. All members must be provided

I am running into this error when trying to Backup a database:
"The media set has 2 media families but only 1 are provided. All
members must be provided."
Please note this is on BACKUP not on restore.
There are a lot of topics on this error for RESTORE, but I didn't find any for BACKUP.
I am using this T.SQL on Sql Server 2005:
backup database dtplog
TO DISK='e:\dtplog.bak'
So it looks like SQL Server has some kind of setting specified there are multiple backup devices for this database.
For some databases I don't get this error, but for some I do.
Any idea what's happening?
This is only for all database backup
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
SET #path = 'C:\Backup\'
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')
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

SQL Server: backup all databases

I was wondering if there was any way of making a backup of an entire SQL Server (we are using SQL Server 2008) at regular intervals to a specific location. I know we are able to backup single specific databases but for ease of use and not having to set up a backup each time I want a new database, is there a way to do this?
If there is however, I must have a way of restoring just a single database from that server backup easily as though I have backed them up individually.
The method used will just be a pure backup and not a difference so no need to worry about complications.
You can run the following script, just change the #path variable to where you want to store the databases.
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
SET #path = 'C:\Backup\'
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')
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
Obtained from:
http://www.mssqltips.com/sqlservertip/1070/simple-script-to-backup-all-sql-server-databases/
Consider backing up hidden resource database as well
Use master
GO
--enable
sp_configure 'show advanced options'
GO
/* 0 = Disabled , 1 = Enabled */
sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE WITH OVERRIDE
GO
--===Resource file details
SELECT 'ResourceDB' AS 'Database Name'
, NAME AS [Database File]
, FILENAME AS [Database File Location]
FROM sys.sysaltfiles
WHERE DBID = 32767
ORDER BY [Database File]
GO
--===Copy resource files
DECLARE #ResDataFile VARCHAR(1000), #ResLogFile VARCHAR(1000)
SELECT
#ResDataFile = CASE NAME WHEN 'Data' THEN FILENAME ELSE #ResDataFile END,
#ResLogFile = CASE NAME WHEN 'Log' THEN FILENAME ELSE #ResLogFile END
FROM sys.sysaltfiles
WHERE DBID = 32767
SELECT #ResDataFile, #ResLogFile
DECLARE #cmd VARCHAR(1000)
--===Copy data file
SELECT #cmd = 'COPY /Y "' + #ResDataFile + '" "G:\SQLBackups"'
--PRINT #cmd
EXEC xp_cmdshell #cmd
--===Copy log file
SELECT #cmd = 'COPY /Y "' + #ResLogFile + '" "G:\SQLBackups"'
--PRINT #cmd
EXEC xp_cmdshell #cmd
GO
--Disable
sp_configure 'show advanced options'
GO
/* 0 = Disabled , 1 = Enabled */
sp_configure 'xp_cmdshell', 0
GO
RECONFIGURE WITH OVERRIDE
GO