先定义表类型:
CREATE TYPE t_bak_tables AS TABLE(table_name VARCHAR(200))
然后再定义备份过程:
CREATE PROC sp_bak_tables @tbs t_bak_tables READONLY, @bak_path VARCHAR(200) ASDECLARE @now VARCHAR(8) = CONVERT(VARCHAR(8),GETDATE(),112), @tb_name VARCHAR(100)DECLARE @bak_db_name VARCHAR(100) = 'db_bak_' + @nowEXEC('CREATE DATABASE ' + @bak_db_name)DECLARE c_tbs CURSOR LOCAL FOR SELECT * FROM @tbsOPEN c_tbsFETCH NEXT FROM c_tbs INTO @tb_nameWHILE @@FETCH_STATUS = 0BEGIN DECLARE @sql VARCHAR(1000) = 'SELECT * INTO ' + @bak_db_name + '.dbo.' + REPLACE(@tb_name,'.','_') + ' FROM ' + @tb_name EXEC(@sql) FETCH NEXT FROM c_tbs INTO @tb_nameENDCLOSE c_tbs DEALLOCATE c_tbsDECLARE @bak_file VARCHAR(100) = @bak_path + 'db_bak_' + @now + '_' + CAST(DATEDIFF(s,{d'1970-01-01'},GETDATE()) AS VARCHAR(100)) + '.bak'EXEC('BACKUP DATABASE ' + @bak_db_name + ' TO DISK = ''' + @bak_file + ''' WITH COMPRESSION')EXEC('DROP DATABASE ' + @bak_db_name)
最后调用方法如下:
DECLARE @tmp_tb bak_tablesINSERT INTO @tmp_tb VALUES ('table_a'),('table_b')EXEC sp_bak_tables @tmp_tb 'D:\BACKUP\'
参考: