SQL Server 数据备份存储过程

﹥>﹥吖頭↗ 提交于 2019-12-04 11:36:30
原文:SQL Server 数据备份存储过程

今天开园,分享一下我一直在使用的数据备份存储过程,欢迎转载!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
USE [master]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER OFF
GO
 
CREATE Proc [dbo].[SQL_Backup]
    @DataBase Nvarchar(50)
AS
DUMP TRANSACTION @DataBase WITH  NO_LOG
BACKUP LOG @DataBase WITH NO_LOG
DBCC SHRINKDATABASE (@DataBase)
 
---------------------------- 原创SQL备份数据库 ----------------------------
--DECLARE @DataBase Nvarchar(100)
DECLARE @DataPath Nvarchar(100)
DECLARE @FileName Nvarchar(100)  
DECLARE @BackupFileName Nvarchar(100)
DECLARE @DataDescription Nvarchar(200)
DECLARE @DataMediaName Nvarchar(50)
DECLARE @DataMediaDescription Nvarchar(200)
DECLARE @OkInfo Nvarchar(300)
DECLARE @str Nvarchar(300)
DECLARE @Rnd Nvarchar(11)
DECLARE @dir Nvarchar(15)
DECLARE @dirin bit
DECLARE @Temp Nvarchar(500)
-- Author: im531...
-- Description: SQL_Backup
-- http://im531.cnblogs.com/
-- Date: 2005-02-06
 
--SET @DataBase = 'test'
SET @Temp = ''
SET @DataPath = 'C:\www\SQL_Backup\'
SET @Rnd = (SELECT Left(Newid(),4) + Right(Newid(),4)) + (SELECT Right(Datepart(ms,Getdate()),3))
SET @str = RTRIM(CONVERT(CHAR(10),GETDATE(),112)) + '_' + RTRIM(DATEPART(HOUR,GETDATE())) + '_' + LTRIM(DATEPART(MINUTE,GETDATE()))
SET @dir = RTRIM(CONVERT(CHAR(10),GETDATE(),112)) + '_' + RTRIM(DATEPART(HOUR,GETDATE()))
SET @FileName = @DataPath + @dir + '\'+ @DataBase + '_Backup_'
SET @BackupFileName = @FileName + @str  + '_' + @Rnd
 
CREATE TABLE [#tb](a bit,b bit,c bit)
SET @Temp = @DataPath + @dir
INSERT INTO [#tb] EXECUTE master..xp_FileExist @Temp
IF Exists(SELECT 1 FROM [#tb] WHERE b = 1)
    SET @dirin = 1
ELSE
    SET @dirin = 0
DROP TABLE [#tb]
 
SET @Temp = 'md ' + @DataPath + @dir
IF @dirin = 0
    BEGIN
        EXEC master..xp_cmdshell @Temp
    END
 
SET @DataDescription = 'SQL语句产生的备份,备份时间:' + CONVERT(CHAR(19),GETDATE(),121)
SET @DataMediaName = 'im531 Backup ...'
SET @DataMediaDescription = 'Author im531 ... '
SET @OkInfo = '数据库 ' + @DataBase + ' 成功备份至 ' + @BackupFileName
 
BACKUP DATABASE @DataBase TO DISK = @BackupFileName
WITH NOINIT , NOUNLOAD , NOSKIP , STATS = 10 , NOFORMAT ,
NAME = @DataBase , DESCRIPTION = @DataDescription ,
MEDIANAME = @DataMediaName , MEDIADESCRIPTION = @DataMediaDescription
 
 
-- 7z 压缩
IF @DataBase = 'DataName'
    BEGIN
        SET @Temp = 'C:\7-zip\7z.exe a -t7z ' + @DataPath + @dir + '.7z ' + @DataPath + @dir + '\* -mx9 -r'
        EXEC master..xp_cmdshell @Temp
        SET @Temp = 'rd ' + @DataPath + @dir + ' /s/q'
        EXEC master..xp_cmdshell @Temp
    END
 
SELECT @OkInfo AS BackupInfo
------------------- End ---------------------
GO
 
EXEC SQL_Backup @DataBase = N'DataName'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!