如何在SQL Server 2008中检索删除的存储过程,函数,表

时间:2015-01-06 10:42:55

标签: sql-server database sql-server-2008 select stored-procedures

我验证了下面的链接,因为某人(@Oliver)发布了我的问题的副本。但是此查询返回上一个执行脚本。这与我的问题无关。

Last executed queries for a specific database

我有一个带有Sample_Training的数据库,我在其中创建了一个存储过程,稍后我删除了它,现在我想要检索已删除的存储过程。

我是公司员工,因此我没有管理权限

DECLARE @Date_From DATETIME = '2015-01-02'
DECLARE @Date_To DATETIME = '2015-01-05'

SELECT 
    CONVERT(VARCHAR(MAX), SUBSTRING([RowLog Contents 0], 33, LEN([RowLog Contents 0]))) AS [Script]
FROM
    fn_dblog(NULL,NULL)
WHERE 
    [Operation] = 'LOP_DELETE_ROWS' 
    AND [Context] = 'LCX_MARK_AS_GHOST'
    AND [AllocUnitName] = 'sys.sysobjvalues.clst'
    AND [TRANSACTION ID] IN (SELECT DISTINCT [TRANSACTION ID] 
                             FROM sys.fn_dblog(NULL, NULL)
                             WHERE Context IN ('LCX_NULL') AND Operation IN ('LOP_BEGIN_XACT') 
                               AND [Transaction Name] = 'DROPOBJ'
                               AND CONVERT(NVARCHAR(11), [Begin Time]) BETWEEN @Date_From AND @Date_To)
                               AND SUBSTRING([RowLog Contents 0], 33, LEN([RowLog Contents 0])) <> 0

通过上面的查询,我可以获得存储过程,现在我的问题是如何获取函数,表。

1 个答案:

答案 0 :(得分:17)

我得到了解决问题的方法。首先需要创建一个程序

CREATE PROCEDURE [dbo].[sp_Recover_Dropped_Objects]
    @Database_Name NVARCHAR(MAX),
    @Date_From DATETIME,
    @Date_To DATETIME
AS

DECLARE @Compatibility_Level INT

SELECT @Compatibility_Level=dtb.compatibility_level
FROM master.sys.databases AS dtb WHERE dtb.name=@Database_Name

IF ISNULL(@Compatibility_Level,0)<=80
BEGIN
    RAISERROR('The compatibility level should be equal to or greater SQL SERVER 2005 (90)',16,1)
    RETURN
END

Select [Database Name],Convert(varchar(Max),Substring([RowLog Contents 0],33,LEN([RowLog Contents 0]))) as [Script]
from fn_dblog(NULL,NULL)
Where [Operation]='LOP_DELETE_ROWS' And [Context]='LCX_MARK_AS_GHOST'
And [AllocUnitName]='sys.sysobjvalues.clst'
AND [TRANSACTION ID] IN (SELECT DISTINCT [TRANSACTION ID] FROM    sys.fn_dblog(NULL, NULL)
WHERE Context IN ('LCX_NULL') AND Operation in ('LOP_BEGIN_XACT') 
And [Transaction Name]='DROPOBJ'
And  CONVERT(NVARCHAR(11),[Begin Time]) BETWEEN @Date_From AND @Date_To)
And Substring([RowLog Contents 0],33,LEN([RowLog Contents 0]))<>0

执行以下程序

EXEC sp_Recover_Dropped_Objects 'Sample_Training','2015/12/24','2015/01/07'