简体   繁体   中英

Azure SQL Database: Clean or restore database via SQL script

We have a windows on-premise scheduled task that we need to migrate to Azure Paas.

The scope of the task is to restore a clean version of the same database daily to improve site's performance.

The task action is to run a batch file, with the below script.

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"

The requirement is to implement a similar functionality by creating an Azure C# WebJob project via Visual Studio and publish it as an Azure WebJob.
Only the schema of the database should remain, no data or logs.

    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();
        }
    }

Is the above possible? What SQL commands can we use for queryString_RestoreMyDatabase to achieve as per title of this post?

Instead of RESTORE, you can copy a database:

-- 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

To replace a database with a copy of an existing database you could start with something like this:

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM