CREATE procedure [dbo].[usp_BackupAllDB]
@databasename varchar(50)=null,@backupdir varchar(100) =nullas
if @backupdir is nullset @backupdir='G:\sqldata\mssql\backup'set nocount ondeclare @dbname varchar(50),@stime varchar(20),@fname varchar(100),@cmd varchar(200),@sql varchar(1000)if @databasename is not null
declare mycursor cursor forselect name from master..sysdatabases where name=@databasenameelsedeclare mycursor cursor forselect namefrom master.sys.databaseswhere database_id not in (2,3) and state_desc ='ONLINE'order by nameopen mycursor
fetch next from mycursor into @dbnamewhile @@fetch_status =0beginselect @cmd = "exec master..xp_cmdshell 'if not exist "+@backupdir+"\"+@dbname+ " md "+@backupdir+"\"+@dbname+"'"--select @cmdexec (@CMD)select @stime=replace(replace(replace(convert(varchar(19),getdate(),120),':',''),' ',''),'-','')
select @sql=" backup database "+@dbname +" to disk='"+@backupdir+"\"+@dbname+"\"+@dbname+"_"+@stime+"_D.BAK' WITH COMPRESSION"exec (@sql)select @sqlfetch next from mycursor into @dbnameendclose mycursordeallocate mycursor set nocount off