Introduction – This blog post illustrates the method through which you can import your database schema and tables into empty Azure SQL DB ( PaaS ) programmatically. Currently azure SQL DB support import from BACPAC file in PowerShell and GUI but not from .SQL files.
Assumptions – Here we assume that you already have .SQL files generated from on-premise data base and ready to upload to azure SQL DB.
Problem statement – I had a requirement where I needed to import schema and tables into empty azure SQL DB from .SQL files. Currently Azure only provides import of BACPAC files out of the box from PowerShell and GUI and from SQL management studio but requirement here was to do it programmatically every time the ARM deployment script creates new azure SQL DB .
Resolution/Workaround – Below steps you should follow
1. Install SQLCMD on the VM/desktop from where you are running the script or deployment. SQLCMD cmdlets are used to deploy SQL files into Azure SQL DB. ODBC driver is required for installing SQLCMD
2. Save all the SQL files into a folder in local VM.
3. Get the public IP of you local VM/desktop using below code.
$IP = Invoke-WebRequest checkip.dyndns.com
$IP1 = $IP.Content.Trim()
$IP2 = $IP1.Replace("<html><head><title>Current IP Check</title></head><body>Current IP Address: ","")
$FinalIP = $IP2.Replace("</body></html>","")
4. Create a new firewall rule to connect to SQL server.
New-AzureRmSqlServerFirewallRule –FirewallRuleName $rulename -StartIpAddress $FinalIP -EndIpAddress $FinalIP –servername $SQLservername –Resourcegroupname $resourcegroupname.
5. Save SQL server full name and sqlcmd path into a variable.
$Fullservername = $SQLservername + '.database.windows.net'
$sqlcmd = "C:Program FilesMicrosoft SQL ServerClient SDKODBC110ToolsBinnSQLCMD.EXE"
6. Save SQL server credentials and Azure SQL DB name in variables.
$username = “SQLusername”
$password = “SQLpassword”
$dbname = “databasename”
7. Run the below command for each SQL files if u want to import it sequentially.
& $sqlcmd -U $username -P $password -S $Fullservername -d $dbname -I -i "C:SQLfile1.sql"
& $sqlcmd -U $username -P $password -S $Fullservername -d $dbname -I -i "C:SQLfile3.sql"
& $sqlcmd -U $username -P $password -S $Fullservername -d $dbname -I -i "C:SQLfilen.sql"
NOTE – You can accumulate all the code and use it in deployment scripts along with functions and error logging
Thanks folks, Hope it is useful.