+ All Categories
Home > Documents > Backup and Restore

Backup and Restore

Date post: 06-Jan-2016
Category:
Upload: rahul-yerrabelli
View: 239 times
Download: 0 times
Share this document with a friend
Description:
BKUP

of 15

Transcript

--SECURITY-- NOTE:| (vertical bar) = Separates syntax items within brackets or braces. You can choose only one of the items.[ ](brackets)= Optional syntax items. Do not type the brackets.{ }(braces)= Required syntax items. Do not type the braces.[,...n]= Indicates the preceding item can be repeated n number of times.The occurrences are separated by commas.[...n] = Indicates the preceding item can be repeated n number of times.The occurrences are separated by blanks.[;]= Optional Transact-SQL statement terminator.Do not type the brackets. ::= The name for a block of syntax. This convention is used to group and label sections of lengthy syntax or a unit of syntax that can be used in more than one location within a statement.Each location in which the block of syntax can be used is indicated with the label enclosed in chevrons: .

--It displays the what are the logins available in SQL SERVER--Syslogins is the table available in Master databaseCMD> select * from syslogins

--It display the current userCMD> select user_name()

--It shows the user informationCMD> sp_helpuserCMD> sp_helpuser manoharreddy

--Through this we can identify how many server roles available in sql server with descriptionCMD> sp_helpsrvrole

--we can identify the specified server role descriptionCMD> sp_helpsrvrole 'sysadmin'

--How many members add this sysadmin roleCMD> sp_helpsrvrolemember 'sysadmin'CMD> sp_helpsrvrolemember 'dbcreator'

--What he can doCMD> sp_srvrolepermissionCMD> sp_srvrolepermission 'sysadmin'CMD> sp_srvrolepermission 'dbcreator'

--We can identify what rights have been granted in a database--Here mano is the databaseCMD> use manoCMD> sp_helprotect

--CREATING LOGINS----Through T-SQL creating the logins--Syntax is CREATE LOGIN login_name { WITH | FROM } ::= WINDOWS [ WITH [ ,... ] ] | CERTIFICATE certname | ASYMMETRIC KEY asym_key_name ::= PASSWORD = 'password' [ HASHED ] [ MUST_CHANGE ][ , [ ,... ] ] ::= SID = sid | DEFAULT_DATABASE = database | DEFAULT_LANGUAGE = language | CHECK_EXPIRATION = { ON | OFF} | CHECK_POLICY = { ON | OFF} [ CREDENTIAL = credential_name ] ::= DEFAULT_DATABASE = database | DEFAULT_LANGUAGE = language

--creating the login from windows(OS)--If we want to create the login for windows authentication mode we should have to OS logins --otherwise we can't create the logins for windows authentication mode--In the below example mano is the login name then that name should be available in the OS login --otherwise we can't create the loginCMD> create login mano from windows

--Creating the login for SQL Server Authentication modeCMD> create login manoharreddy with password='m', DEFAULT_DATABASE=master,default_language=french, check_expiration=on,check_policy=on

--must_change option not supported in XPCMD> create login mano with password='m' must_change, DEFAULT_DATABASE=master, default_language=french,check_expiration=on,check_policy=on

--Creating the logins through SystemProcedure--Syntax is sp_addlogin [@loginame=]'login',[@passwd=]'password', [@defdb= ]'database',[@deflanguage= ]'language',[@sid = ] sid,[ @encryptopt= ] 'encryption_option' ] CMD> sp_addlogin 'mano'CMD> sp_addlogin 'mano1','m'CMD> sp_addlogin 'mano2','m','master'CMD> sp_addlogin 'mano3','m','msdb','french'--ALTERING THE LOGING----Altering the logins--Syntax isALTER LOGIN login_name {

| WITH [ ,... ] } ::= ENABLE | DISABLE ::= PASSWORD = 'password' [ OLD_PASSWORD = 'oldpassword' | [ ] ] | DEFAULT_DATABASE = database | DEFAULT_LANGUAGE = language | NAME = login_name | CHECK_POLICY = { ON | OFF } | CHECK_EXPIRATION = { ON | OFF } | CREDENTIAL = credential_name | NO CREDENTIAL ::= MUST_CHANGE | UNLOCK

--Disable the login CMD> alter login manoharreddy disable

--Enable the login CMD> alter login manoharreddy enable

--change the login passwordCMD> alter login manoharreddy with password='reddy' old_password='m'

--Change the login nameCMD> alter login manoharreddy with name=manoharreddy_B

--Change the password it works even we does't mention oldpasswordCMD> alter login manoharreddy_B with password='reddy'

--Altering the logins through SystemProcedure--Syntax is sp_password [[ @old = ] 'old_password',]{ [ @new =] 'new_password' } [ , [ @loginame = ] 'login' ]

--Change passwordCMD> sp_password 'm','mm','mano1'--DELETING LOGINS----Delete the loginsCMD> drop login manoCMD> drop login manoharreddyCMD> drop login manoharreddy_B--CREATING/DROPPING USERS----Creating the user through T-SQL--Syntax isCREATE USER user_name [ { { FOR | FROM }{ LOGIN login_name | CERTIFICATE cert_name | ASYMMETRIC KEY asym_key_name } | WITHOUT LOGIN] [ WITH DEFAULT_SCHEMA = schema_name ]

--Creating the user for manoharreddy_B loginCMD> create user reddy for login manoharreddy_B--Creating the user through SystemProcedure--Syntax is sp_adduser [ @loginame = ] 'login' [ , [ @name_in_db = ] 'user' ] [ , [ @grpname = ] 'role' ]

--Altering the User through T-SQL--Syntax isALTER USER user_name WITH [ ,...n ] ::= NAME = new_user_name | DEFAULT_SCHEMA = schema_name--Alter the userCMD> alter user reddy with name=manoharreddy

--Deleting the user--Syntax isDROP USER user_name

CMD> drop user manoharreddy

--It shows the user informationCMD> sp_helpuserCMD> sp_helpuser manoharreddy--ADDING/DROPPING SERVER ROLES----Through this we can identify how many server roles available in sql server with descriptionCMD> sp_helpsrvrole

--we can identify the specified server role descriptionCMD> sp_helpsrvrole 'sysadmin'

--We can add/drop the server role to specified login--Add role syntax is sp_addsrvrolemember 'loginname','serverrole'--Drop role syntax is sp_dropsrvrolemember 'loginname','serverrole'CMD> sp_addsrvrolemember 'manoharreddy','bulkadmin'CMD> sp_dropsrvrolemember 'manoharreddy','bulkadmin'

CMD> sp_addsrvrolemember 'manoharreddy','dbcreator'CMD> sp_dropsrvrolemember 'manoharreddy','dbcreator'

CMD> sp_addsrvrolemember 'manoharreddy','diskadmin'CMD> sp_dropsrvrolemember 'manoharreddy','diskadmin'

CMD> sp_addsrvrolemember 'manoharreddy','processadmin'CMD> sp_dropsrvrolemember 'manoharreddy','processadmin'

CMD> sp_addsrvrolemember 'manoharreddy','securityadmin'CMD> sp_dropsrvrolemember 'manoharreddy','securityadmin'

CMD> sp_addsrvrolemember 'manoharreddy','serveradmin'CMD> sp_dropsrvrolemember 'manoharreddy','serveradmin'

CMD> sp_addsrvrolemember 'manoharreddy','setupadmin'CMD> sp_dropsrvrolemember 'manoharreddy','setupadmin'

CMD> sp_addsrvrolemember 'manoharreddy','sysadmin'CMD> sp_dropsrvrolemember 'manoharreddy','sysadmin'

--How many LOGINS add this server roleCMD> sp_helpsrvrolemember 'sysadmin'CMD> sp_helpsrvrolemember 'dbcreator'

--What he can doCMD> sp_srvrolepermissionCMD> sp_srvrolepermission 'sysadmin'CMD> sp_srvrolepermission 'dbcreator'

--GRANT,DENY,REVOKE permissions ON DATABASE /OBJECTS----GRANT:: gives a user permission to perform certain tasks on Database objects--DENY :: denies any access to a user to perform certain tasks on database objects--REVOKE: removes a grant or deny permission from a user on certain database objects

CMD> create database mano

--We can identify what rights have been granted in a databaseCMD> use manoCMD> sp_helprotect

--We can also grant users permissions to do other tasks such as create tables,views,stored procedures,....CMD> grant create table to manoharreddy

--Grants permissions on a database.--Syntax isGRANT [ ,...n ] TO [ ,...n ] [ WITH GRANT OPTION ] [ AS ]::= permission | ALL [ PRIVILEGES ] ::= Database_user | Database_role | Application_role | Database_user_mapped_to_Windows_User | Database_user_mapped_to_Windows_Group | Database_user_mapped_to_certificate | Database_user_mapped_to_asymmetric_key | Database_user_with_no_login

--through this we can grant the permission on database levelCMD> grant insert to manoharreddy

--Grants permissions on a database user, database role, or application role.--Syntax isGRANT permission [ ,...n ] ON { [ USER :: database_user ] | [ ROLE :: database_role ] | [ APPLICATION ROLE :: application_role ] } TO [ ,...n ] [ WITH GRANT OPTION ] [ AS ] ::= Database_user | Database_role | Application_role | Database_user_mapped_to_Windows_User | Database_user_mapped_to_Windows_Group | Database_user_mapped_to_certificate | Database_user_mapped_to_asymmetric_key | Database_user_with_no_login

--Grants permissions on a table, view, table-valued function, stored procedure,extended stored procedure, scalar function, aggregate function, service queue, or synonym--Syntax isGRANT [ ,...n ] ON [ OBJECT :: ][ schema_name ]. object_name [ ( column [ ,...n ] ) ] TO [ ,...n ] [ WITH GRANT OPTION ] [ AS ] ::= ALL[ PRIVILEGES] | permission[( column [ ,...n ] ) ] ::= Database_user | Database_role | Application_role | Database_user_mapped_to_Windows_User | Database_user_mapped_to_Windows_Group | Database_user_mapped_to_certificate | Database_user_mapped_to_asymmetric_key | Database_user_with_no_login

--Enter into the specified database then give the permissions--allow users mano,manoharreddy to select,insert & update data on table empCMD> Use manoCMD> grant insert,update,select on emp to manoharreddy,mano

--Denies permissions on a database.--Syntax isDENY [ ,...n ] TO [ ,...n ] [ CASCADE ] [ AS ] ::= permission | ALL [ PRIVILEGES ] ::= Database_user | Database_role | Application_role | Database_user_mapped_to_Windows_User | Database_user_mapped_to_Windows_Group | Database_user_mapped_to_certificate | Database_user_mapped_to_asymmetric_key | Database_user_with_no_login

--Deny delete access to table hostel for user mano,manoharreddyCMD> Use manoCMD> deny update on emp to mano,manoharreddy

--Revokes permissions granted and denied on a database--Syntax isREVOKE [ GRANT OPTION FOR ] [ ,...n ] { TO | FROM } [ ,...n ] [ CASCADE ] [ AS ] ::= permission | ALL [ PRIVILEGES ] ::= Database_user | Database_role | Application_role | Database_user_mapped_to_Windows_User | Database_user_mapped_to_Windows_Group | Database_user_mapped_to_certificate | Database_user_mapped_to_asymmetric_key | Database_user_with_no_login

--Remove update access to table emp for user manoCMD> Use manoCMD> revoke update on emp to manoRecovery modelIt is database level property.sql server supports 3 types of recovery model Full bulk logged simpleFull: in full recovery model every transaction is recorded in t.log file. log file grow very fast, to control log file growth we have to congfigure regular log backups we can recovery data when the database is failed we can configure all types of backups. we can configure log-shipping,db mirroring for user defined databases always its reveory model should be full.Simple: every transaction is recovered in t.log file log is truncated once check point. no log backups are allowed only full and diff backup are allowed no log-shipping and mirroring is supported.Bull logged: Log file is truncated at the time of log backup bulk logged recovery model minimally logs bulk opertation althought fully logged other transaction if data file was damaged then there is chance to lose bulk transction. only log-shipping possible

alter database dbname set recovery fullselect * from sys.databasesselect databasepropertyex('test'.'recovery')

backup:backup is nothing but copy of orginal data.types of backup: full diff tlog file or filgroup mirror split copy_only taillog compression backupsbackup can be generated in two types of files1)*.bak(can consists of any type of backup)2)*.trn(trnasation log backup

We cannot take backup of database whose state is suspect restoring.. stanby offlineif t.log file was full(only log backup are allowed)who can take backuponly members of the following role can take backup sysadmin : can take backup of any database db_owner : can take backup of respective db DB_backupoperator : can take backup of respective dbfullbackup: complete database is backup it taken both data and t.log files into backup takes long time,depends on size of database it is a base for diff and t.log backup.dbcc showfilestats

what is your backup strategy?it depends on size of database revoery model transaction rate availiability(24/7)Q1:my database size is 6 gb and daily 500 trnasaction suggestible stragegy daily full backup every 2 hrs diff every 15 tlog backupQ2:my datbase size 600 GB and daily 30000 trnaction suggetble stragegy. weekly full backup daily diff every 15 mins t.logdiff: changes made after fullback up can be taken into file with diff backup it is generated fast as compared with full backup it captures all extents that have changed since the last full backup it reduces time of recovery in case of database failure no need restore all log backup made after full backuphow it works: changes made after full backup are wirtten into dcm pages which base to take diff backups. when changed are made to extends in the database sql server set the bit corresponding to the extent to 1when diff backup is generated first sql server goes to dcm pages to find changed extends information and write these changes into diff backup

case :Every Sunday i have configured full backup and Diff backupsbackup generated on Friday has all transaction from since last Sunday

D ---full I - diff/incremental F file L --t.log FG -- filegroup

to clear backup history from msdb db can usesp_delete_backphistory '2013-09-13'(date)tlog: Its takes backup of t.log file only it takes all trnaction from the last full or diff or log backup it is possible only in full and bulklogged recovery model when database is failure occurs,we have to apply all log backup genrated ofter recent full and diff1000 --- full ---1 to 10001100 -- tlog ---1001 to 1100Note : t.log backup chain will never break. Because logs are bind with LSN numbers(Log Sequence numbers)

tail-log:it is last transaction log backup which should be taken before restoring database in the event of database failurecan't truncate the t.log

we can take in the following scenarios: if the t.log was not damage physically if the recovery model is other than simple

t.log: this scheduled backup it force checkpoint it trnacate tlogfile can be genrated when the database is online

taillog backup: not scheduled it is taken manully where the database damaged occure no checkpoint no truncated can generated when the database is not online

Q1:every sunday 5am full backup everyday 5am diff and every 15 mints tlog backup, database was failed 5.30 am on Friday then how to recovery db.. take taillog backup to get 5 to 5.30 pm transaction restore the latest sunday full with no recovery resotre latest diff with no recovery restore tail log backup with recoveryQ2: my backup was fialed what may be the possible scenarious. no disk space server was busy msdb was offline agent services are stopped mode net work problem transaction log file is fullSplit:if the size of backup is large where there is no required disk space in any drive we can split backup in to multiple filesbackup db dbname to disk = '',dsik = '',disk = '' with noformat ,stats = 10-------------------BACKUP THE DATABASES ---------------------------------------------FULL:backup database tecno to disk = 'D:\BACKUP\full.bak' with stats = 10DIFFERENTIAL:backup database tecno to disk = 'D:\BACKUP\full.bak' with differential T-LOG:backup log tecno to disk = 'D:\BACKUP\tlog.trn' MIRROR:backup database tecno to disk = 'D:\BACKUP\full.bak' mirror to disk = 'C:\BACKUP\full.bak' with formatCOPY_ONLY:backup database tecno to disk = 'D:\BACKUP\full.bak' with copy_onlyCOMPRESSION:backup database tecno to disk = 'D:\BACKUP\full.bak' with compressionSPLIT:backup database tecno to disk = 'D:\BACKUP\full.bak', disk = 'E:\BACKUP\full.bak', disk = 'F:\BACKUP\full.bak' with noformat, stats = 10

FILE&FILEGROUPBACKUP DATABASE tecno FILEGROUP = 'PRIMARY' TO DISK = 'C:\Primary\full.bak'Tail-log backup log tecno to disk = 'D:\BACKUP\tlog.trn' with no_truncate(note date&time when willu take backup)

----TO GET THE % COMPLETED?select percent_complete, DATABASE_ID from sys.dm_exec_requests----TO KNOW THE BACKUP STATUS?:-use msdbselect * from backupset where type = 'I' and database_name = 'CFS'order by backup_finish_date desc--- how to check transacton log size daywise ?-----------select CONVERT(char(11), backup_start_date) as 'Backup Date',Database_Name as 'Database Name',((sum(compressed_backup_size)/1024)/1024) as 'Backup Size (GB)',type from msdb..backupsetwhere Database_Name = 'imobile3x'andtype = 'L'and backup_start_date between 'apr 1 2013' and 'apr 24 2013'group by CONVERT(char(11), backup_start_date),Database_name,typeorder by CONVERT(char(11), backup_start_date)

select *,CONVERT(char(11), backup_start_date) as 'Backup Date',Database_Name as 'Database Name',backup_size as 'Backup Size (GB)',type from msdb..backupsetwhere Database_Name = 'imobile3x'

============How can I monitor that all Databases are backing up as per plan =======SELECTCONVERT(CHAR(100), 'JPRWINDRESTO') AS Server,bs.database_name,bs.backup_start_date,bs.backup_finish_date,bs.expiration_date,CASE bs.typeWHEN 'D' THEN 'Full Database'WHEN 'L' THEN 'Log'WHEN 'I' THEN 'Differential'WHEN 'F' THEN 'File Level'WHEN 'G' THEN 'File Level Differential'WHEN 'P' THEN 'Partial'WHEN 'Q' THEN 'Differential partial'END AS backup_type,convert(varchar,cast(bs.backup_size/1024/1024 as money),10) as 'Backup Size in MB',bmf.logical_device_name,bmf.physical_device_name,bs.name AS backupset_name,bs.descriptionFROM msdb.dbo.backupmediafamily bmfINNER JOIN msdb.dbo.backupset bs ON bmf.media_set_id = bs.media_set_idWHERE (CONVERT(datetime, bs.backup_start_date, 102) >= GETDATE() - 10)ORDER BYbs.database_name,bs.backup_finish_date=====monitor What all Databases are not being backup in last 24 hours========SELECTCONVERT(CHAR(100), 'JPRWINDRESTO') AS Server,bs.database_name,MAX(bs.backup_finish_date) AS last_db_backup_date,DATEDIFF(hh, MAX(bs.backup_finish_date), GETDATE()) AS [Backup Age (Hours)]FROM msdb.dbo.backupset bsWHERE bs.type = 'D'GROUP BY bs.database_nameHAVING (MAX(bs.backup_finish_date) < DATEADD(hh, - 48, GETDATE()))USE msdb;SELECT physical_name FROM sys.database_filesGO-- Find last FUll backup datetime and path?--select top 1 bs.backup_finish_date, bs.database_name, bs.server_name, bmf.physical_device_namefrom msdb.dbo.backupset bsinner join msdb.dbo.backupmediafamily bmf on bs.media_set_id = bmf.media_set_idwhere bs.database_name = 'HRTFS' and bs.type = 'D' --'L' for log backups ,I difforder by bs.backup_finish_date desc ----------------RESTORE DATABASES ------------------------------------HOW TO VERIFY BACKUP FILE?---restore VERIFYONLY from disk = 'D:\Backup\LOMBARD.bak'--HOW TO FINDOUT DATAFILES LOCATION FROM BACKUP?---restore FILELISTonly from disk='D:\BACKUP\FULL_LOMBARD_201506171141.BAK'--HOW TO RESTORE DATABASE?--RESTORE DATABASE LOMBARD FROM DISK='D:\BACKUP\FULL_LOMBARD_201506171141.BAK' WITH NORECOVERY (FOR FULL BACKUP)RESTORE DATABASE LOMBARD FROM DISK='D:\BACKUP\FULL_LOMBARD_201506171141.BAK' WITH RECOVERY(FOR LAST TLOG/TAIL-LOG)---HOW TO FINDOUT PERTICULAR DATABASE BACKUP INFORMATION?-----restore HEADERonly fromdisk='D:\BACKUP\FULL_LOMBARD_201506171141.BAK'--HOW TO RESTORE DATABASE IN SAME AS PREVIOUS LOCATION?--restore database LOMBARD from disk ='D:\BACKUP\FULL_LOMBARD_201506171141.BAK'with MOVE 'LOMBARD' to 'D:\MSSQL10_50.SQL2008R2\MSSQL\DATA\LOMBARD.mdf',MOVE 'LOMBARD_log' to 'D:\MSSQL10_50.SQL2008R2\MSSQL\DATA\LOMBARD_log.ldf'--HOW TO KNOW TOTAL DATABASES BACKUPS INFORMATION?--select backup_start_date,backup_finish_date from backupset where database_name = 'subscriber' and type = 'D'What is SQL Server log shipping?SQL Server log shipping is a technique which involves two or more SQL Server instances and copying of a transaction log file from one SQL Server instance to another. The process of transferring the transaction log files and restoring is automated across the SQL Servers. As the process result there are two copies of the data on two separate locations

A log shipping session involves the following steps: Backing up the transaction log file on theprimarySQL Server instance Copying the transaction log backup file across the network to one or moresecondarySQL Server instances Restoring the transaction log backup file on thesecondarySQL Server instancesImplementation examplesOne of the common log shipping scenarios is the environment with two servers (SQLServer-1 primaryand SQLServer-2 secondary), two SQL Server instances (SQLInstance-1 and SQLInstance-2), and one SQL Server database named SQLDB-1 with log shipping running on it

Another common configuration is the environment with three (or more) servers (SQLServer-1 primary, SQLServer-2 secondary, and SQLServer-3 secondary), three SQL Server instances (SQLInstance-1, SQLInstance-2, and SQLInstance-3), and one SQL Server database named SQLDB-1 with log shipping running on it

Operating modesThere are two available modes and they are related to the state in which the secondary, log shipped, SQL Server database will be: Standby mode the database is available for querying and users can access it, but in read-only mode The database is not available only while the restore process is running Users can be forced to disconnect when the restore job commence The restore job can be delayed until all users disconnect themselves Restore mode the database is not accessibleAdvantages and disadvantages of using SQL Server log shippingSQL Server log shipping is primarily used as a disaster recovery solution. Using SQL Server log shipping has multiple benefits: its reliable and tested in details, its relatively easy to set up and maintain, there is a possibility for failover between SQL Servers, data can be copied on more than one location etc.Log shipping can be combined with other disaster recovery options such as AlwaysOn Availability Groups, database mirroring, and database replication. Also, SQL Server log shipping has low cost in human and server resourcesThe main disadvantages in the SQL Server log shipping technique are: need to manage all the databases separately, there isnt possibility for an automatic failover, and secondary database isnt fully readable while the restore process is runningSetting up the database log shipping environmentSQL Server log shipping is based on execution of predefined SQL Server jobs. The SQL Server log shipping feature is available in all SQL Server editions except the Express edition. All the databases intended to be used for log shipping must be in the Full or Bulk logged recovery modelAnother important prerequisite is running SQL Server Agent on both servers. Security policies must be defined in order for SQL Server Agent to have permission to read and write in the backup folder. Note that SQL Server agent on the secondary server must be able to read from the primary servers backup folderThe database backups can be compressed, but that requires additional CPU time. Most common configurations use network locations for storing the backupsThe database log shipping setup needs to be initiated from the principal server using the SQL Server Management Studio wizard. The first step defines transaction log backup settings: A network path to the backup How long backup files should be kept before deleting An alert if no backup is taken The backup job itself Schedule of the job Schedule type Frequency Duration

The next step defines secondary databases which involve choosing the secondary SQL Server instance and secondary database. The full database backup, from the primary database, must be restored on the secondary server before log shipping commences

After initializing the secondary database you must define the copy folder where the transaction log backups from the primary server will be storedThe final step involves choosing from two available modes: The No recovery Restore mode and Standby mode. You can also delay the restoring process and set up an alert if no restore occurs within the specified time

Once the log shipping is ready for use, it will run in the background, and if the problem occurs the alert will signalize the problem


Recommended