0

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_RestoreMyDatabaseto achieve as per title of this post?

Jayendran
  • 9,638
  • 8
  • 60
  • 103
alex
  • 1,300
  • 1
  • 29
  • 64

1 Answers1

1

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'
David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67
  • Thank you David, what about replacing the existing database, will this require creating a new database that does not exist having a different name and what about the references in code to the current database? – alex Nov 24 '18 at 18:58
  • Thank you, David, for your time, it works. Noticed that the script takes ~ 6 minutes to complete, assuming this is normal? considering a new database needs to be created? – alex Nov 26 '18 at 18:43
  • Do you know what will the costs be in Azure to run this once every day. Asked a new question here: https://stackoverflow.com/questions/54460615/azure-sql-what-is-the-cost-of-running-a-specific-sql-query-like-create-database – alex Jan 31 '19 at 12:44