SQL Query to backup database in sql server


Sometimes things that seem complicated are much easier then you think and this is the power of using T-SQL to take care of repetitive tasks.  One of these tasks may be the need to backup the database on your server.   This is not a big deal.  You could use SQL Server Management Studio to backup the database or even use Maintenance Plans, but using T-SQL is a much simpler and faster approach. 

Below is the T-SQL query which i used to back up my database.

-- Backup Database to .bak File
DECLARE @fileName VARCHAR(90);
DECLARE @db_name VARCHAR(20);
DECLARE @fileDate VARCHAR(20);

SET @fileName = 'D:\backups\'; -- change to the relevant path
SET @db_name = 'mydb';     -- change to the relevant database name
SET @fileDate = CONVERT(VARCHAR(20), GETDATE(),112);
SET @fileName = @fileName + @db_name + '_' + RTRIM(@fileDate) + '.bak';

BACKUP DATABASE @db_name TO DISK = @fileName; 


Post a Comment

Online Casino