如何在SQL中为每个循环实现

时间:2019-07-04 20:11:10

标签: sql-server tsql dbo

如何在SQL中为每个循环实现一个?

我正在寻找一种使用以下名称语法将SQL Server 2019数据库自动备份到给定文件夹的方法:

<Date><DB Name>

我希望能够在临时表中列出所有数据库:

DECLARE @DBList TABLE (DBName VARCHAR(40))

INSERT INTO @DBList 
    SELECT name 
    FROM master.dbo.sysdatabases

,然后运行每个记录代理功能。

目前,这就是我的操作方式。它确实违反了一次写入原则

-- Initialize variables
DECLARE @Date NVARCHAR(MAX) = CONVERT(VARCHAR, GETDATE(), 112);
DECLARE @DBName SYSNAME;
DECLARE @Path NVARCHAR(MAX);

USE [master];

-- BackUp Database
SET @DBName = 'DATABASE01';
SET @Path = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\' + @Date + @DBName +'.bak';
BACKUP DATABASE @DBName TO DISK = @Path;

SET @DBName = 'DATABASE02';
SET @Path = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\' + @Date + @DBName +'.bak';
BACKUP DATABASE @DBName TO DISK = @Path;

SET @DBName = 'DATABASE03';
SET @Path = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\' + @Date + @DBName +'.bak';
BACKUP DATABASE @DBName TO DISK = @Path;

SET @DBName = 'DATABASE04';
SET @Path = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\' + @Date + @DBName +'.bak';
BACKUP DATABASE @DBName TO DISK = @Path;

SET @DBName = 'DATABASE05';
SET @Path = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\' + @Date + @DBName +'.bak';
BACKUP DATABASE @DBName TO DISK = @Path;

1 个答案:

答案 0 :(得分:2)

您可以通过这种方式使用循环。 您需要创建某种排名以遍历每一行,然后根据当前排名获取值。

DECLARE @DBList TABLE (DBName varchar(40),rankvalue int)
insert into @DBList SELECT name, DENSE_RANK() over (order by name) rankval FROM master.dbo.sysdatabases


 Declare @Date NVARCHAR(max) = convert(varchar, getdate(), 112);
DECLARE @DBName SYSNAME;
DECLARE @Path NVARCHAR(MAX);
 Declare @current int = 1   , @maxvalue int =(select max(rankvalue) from  @DBList) 


while @current <= @maxvalue 
begin 
Set @DBName =  (select DBName  from @DBList where rankvalue = @current)
Set @Path = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Backup\' + @Date + @DBName +'.bak';
BACKUP DATABASE @DBName TO DISK = @Path   
set @current = @current + 1 
end