Azure SQL数据库:通过SQL脚本清理或还原数据库

时间:2018-11-23 11:36:43

标签: c# azure azure-sql-database

我们有一个Windows本地计划任务,需要将其迁移到Azure Paas。

任务的范围是每天恢复同一数据库的干净版本,以提高站点的性能。

任务操作是使用以下脚本运行批处理文件。

SQLCMD -E -S server-name -Q "use master; alter database myDatabase set 
single_user with rollback immediate; alter database myDatabase set 
multi_user; RESTORE DATABASE myDatabase FROM DISK='C:\Dir\myDatabase.bak'; 
USE myDatabase; CREATE USER myUser FOR LOGIN myUser; USE myDatabase; ALTER 
ROLE db_owner ADD MEMBER myUser"

要求是通过通过Visual Studio创建Azure C#WebJob项目并将其发布为Azure WebJob来实现类似的功能。
只保留数据库的架构,不保留数据或日志。

    using (SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["AzureDBConnString"]))
    {
        connection.Open();

        var queryString_RestoreMyDatabase = @"?????"; // what to add here?

        using (SqlCommand cmd_RestoreMyDatabase = new SqlCommand(queryString_RestoreMyDatabase, connection))
        {
            cmd_RestoreMyDatabase.ExecuteNonQuery();
        }
    }

以上可能吗?根据帖子的标题,queryString_RestoreMyDatabase可以使用哪些SQL命令来实现?

1 个答案:

答案 0 :(得分:1)

您可以复制数据库来代替RESTORE:

-- Execute on the-- Execute on the master database.
-- Start copying.
CREATE DATABASE Database2 AS COPY OF Database1;

Copy an transactionally consistent copy of an Azure SQL database

要将数据库替换为现有数据库的副本,您可以从以下内容开始:

if  exists (select state from sys.databases where name = 'test_new')
begin
  drop database test_new;
end

create database test_new as copy of test_template;
while (0 != coalesce((select state from sys.databases where name = 'test_new'),-1 ))
begin
  waitfor delay '0:0:10'
end

alter database test modify name = test_old;
alter database test_new modify name = test;
drop database test_old;
print 'completed sucessfully'