title: script how to get last backup to restore from AZURE
body: <p>I want to restore the last backup from mu AZURE server. I have one script but just I achieve to take the backup with current date but not the last one. Do you have any idea how to get it?</p>
  
  <p>`USE [master]
  GO
  DECLARE @name VARCHAR(50) -- database name<br>
  DECLARE @URL VARCHAR(256) -- URL for backup<br>
  DECLARE @fileDate VARCHAR(20) -- used for file date</p>
  
  <p>-- specify date format to take the last backup.
  SELECT @fileDate = REPLACE (CONVERT (VARCHAR (10), GETDATE (), 120), '-','_')</p>
  
  <p>--Create a credential to connect to the windows azure storage service
  IF NOT EXISTS (SELECT * FROM sys.credentials WHERE credential_identity = 'aaaaaaaaaa')
  BEGIN
  CREATE CREDENTIAL Pyramidsqlcredential WITH IDENTITY = 'bbbbbbbbbb'
  ,SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  END
  GO</p>
  
  <p>--Code to be able to restore specific databases
  DECLARE db_cursor CURSOR FOR<br>
  SELECT name 
  FROM master.dbo.sysdatabases 
  WHERE name IN ('STG','DWH','AUXDB','TESTPORTAL')  -- only restore these databases</p>
  
  <p>OPEN db_cursor<br>
  FETCH NEXT FROM db_cursor INTO @name
  WHILE @@FETCH_STATUS = 0<br>
  BEGIN </p>
  
  <p>--Creation of PRE databases
  IF  OBJECT_ID(N'PRE_@name', N'U') IS NOT NULL 
     DROP DATABASE @name;
  GO
  CREATE DATABASE [@name]
   CONTAINMENT = NONE
   ON  PRIMARY 
  ( NAME = N'PRE_@name', FILENAME = N'G:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Data\PRE_@name.mdf' , SIZE = 609344KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ), 
   FILEGROUP [INMEMORY] CONTAINS MEMORY_OPTIMIZED_DATA  DEFAULT
   LOG ON 
  ( NAME = N'PRE_@name', FILENAME = N'H:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Data\PRE_@name_log.ldf' , SIZE = 833024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)</p>
  
  <p>set @URL = '<a href="https://xxxxxxxxxx.blob.core.windows.net/" rel="nofollow">https://xxxxxxxxxx.blob.core.windows.net/</a>'</p>
  
  <p>--RESTORE the database to the windows azure storage service - blob using URL
  RESTORE DATABASE PRE_AUXDB 
  FROM URL = @URL+@name+'/'+@name+'<em>'+@fileDate+'*.bak'
  --FROM URL = '<a href="https://xxxxxxxxxxxxxxxxxxxxxxx.blob.core.windows.net/AUXDB/AUXDB_" rel="nofollow">https://xxxxxxxxxxxxxxxxxxxxxxx.blob.core.windows.net/AUXDB/AUXDB</em></a>'+REPLACE (CONVERT (VARCHAR (10), GETDATE (), 120), '-','_')+'*.bak'
  WITH CREDENTIAL = 'aaaaaaaaaaaaaaa'
  ,MOVE 'PRE_AUXDB_Data' to 'G:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Data\PRE_@name_Data.mdf'
  ,STATS = 10</p>
  
  <p>END   </p>
  
  <p>CLOSE db_cursor<br>
  DEALLOCATE db_cursor`</p>