存储Proc:Sql服务器表备份

时间:2019-01-29 12:59:52

标签: sql-server stored-procedures cursor

我需要循环遍历INFORMATION_SCHEMA.TABLES中的表列表 对于每个table_name输出,我需要使用数据创建一个单独的新表。

Ex : SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES where table_Name in 
('EMP','DEPT','SAL')

“我的程序”应该删除旧表名(如果存在的话),并创建三个新表,并在上述结果中加上systemdate

drop BKP_<Table_Name>_* //*Drop Old tables which are one week older with 
systemdate <=(sysdate-7))
select * into BKP_<Table_Name>_<SYSTEMDATE> FROM <Table_Name> ;

能帮忙

1 个答案:

答案 0 :(得分:0)

逻辑示例。

仍然可以进行一些调整,例如错误处理,更好的日志记录或要传递的其他参数-表列表。但可以作为进一步步骤的起点

CREATE  PROCEDURE usp_BackupTable
@RetentionDays int = 7
AS 

DECLARE @_tbl sysname, @_schema sysname, @_sql_Backup VARCHAR(400), @_sql_Drop VARCHAR(400);


-- first part: create backups of listed tables
DECLARE ct CURSOR FOR 
SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME IN  ('ETLSettings')  AND TABLE_TYPE = 'BASE TABLE'


OPEN ct
FETCH NEXT FROM ct INTO @_schema, @_tbl

WHILE @@FETCH_STATUS = 0

BEGIN    
    SET @_sql_Backup = 'SELECT * INTO ['+@_schema+'].BKP_'+@_tbl+'_'+CONVERT(varchar(20), GETDATE(), 112)+' FROM ['+@_schema+'].['+@_tbl+'] ;'
    EXEC (@_sql_Backup)
    PRINT 'Backup of table ' + @_tbl + ' has been created'
FETCH NEXT FROM ct INTO @_schema, @_tbl 
END

CLOSE ct
DEALLOCATE ct


-- second part: cleanup of backups
DECLARE ct CURSOR FOR 
SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'BKP%[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]' AND TABLE_TYPE = 'BASE TABLE'
AND TRY_CAST(RIGHT(TABLE_NAME, 8) AS DATETIME ) < CAST(GETDATE()-@RetentionDays AS DATE)

OPEN ct
FETCH NEXT FROM ct INTO @_schema, @_tbl

WHILE @@FETCH_STATUS = 0
BEGIN    
    SET @_sql_Drop = 'DROP TABLE ['+@_schema+'].['+@_tbl+'] ;'
    EXEC (@_sql_Drop)

    PRINT 'Table ' + @_tbl + ' has been deleted'
FETCH NEXT FROM ct INTO @_schema, @_tbl 
END

CLOSE ct
DEALLOCATE ct