自动备份SQL Server数据库中用户创建的Stored Procedures
为了避免意外丢失/损坏辛苦创建的Stored Procedures,或者想恢复到以前版本的Stored Procedures,这样提供了一个有效方法,可以自动将指定数据库中的Stored Procedures进行备份。
1. 在特定的数据库(建议为SQL Server的master数据库)上创建数据表StoredProceduresBackup,用来保存备份的Stored Procedures。
IF OBJECT_ID('StoredProceduresBackup') IS NOT NULL
DROP TABLE StoredProceduresBackup
GO
CREATE TABLE StoredProceduresBackup
(
AutoID INTEGER IDENTITY(1,1) PRIMARY KEY,
InsertDate DATETIME DEFAULT GETDATE(),
DatabaseName VARCHAR(50),
ProcedureName VARCHAR(50),
ProcedureText VARCHAR(4000)
)
GO
2. 创建Stored Procedure名为usp_ProceduresVersion,该Stored Procedure用来将需要备份Stored Procedures的备份到上述创建的数据表中。
其中主要访问sysobjects和syscomments系统表:
(1) sysobjects system table
Contains one row for each object (constraint, default, log, rule, stored procedure, and so on) created within a database. In tempdb only, this table includes a row for each temporary object.
(2) syscomments system table
Contains entries for each view, rule, default, trigger, CHECK constraint, DEFAULT constraint, and stored procedure. The text column contains the original SQL definition statements, which are limited to a maximum size of 4 MB. This table is stored in each database.
(3) source script of stored procedure.
/*
Name: usp_ProceduresVersion
Description: Back up user defined stored-procedures
Author: Rickie
Modification Log: NO
Description Date Changed By
Created procedure 8/27/2004 Rickie
*/
CREATE PROCEDURE usp_ProceduresVersion @DatabaseName NVARCHAR(50)
AS
SET NOCOUNT ON
--This will hold the dynamic string.
DECLARE @strSQL NVARCHAR(4000)
--Set the string
--Only stored procedures
SET @strSQL = 'INSERT INTO master.dbo.StoredProceduresBackup(
DatabaseName,ProcedureName,ProcedureText )
SELECT ''' + @DatabaseName + ''', so.name, sc.text
FROM ' + @DatabaseName + '.dbo.sysobjects so
INNER JOIN ' + @DatabaseName + '.dbo.syscomments sc
ON so.id = sc.id
WHERE so.type = ''p''' + ' and so.status>0
Order By so.id '
--Execute the string
EXEC dbo.sp_executesql @strSQL
GO
3. 创建Job执行上述Stored Procedure
在SQL Server上创建Job,并设定运行计划,这样指定数据库的Stored Procedures就可以自动备份到上述数据表中。
OK. That’s all. Any questions about it, please contact me at rickieleemail@yahoo.com. Have a good luck.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?