Hands-OnLab
MigratingDatabasestoSQLAzure
Labversion:2.0.0
Lastupdated:11/15/2018
Contents
Overview
Exercise 1: Moving an Existing Database to the Cloud
Task 1 – Provisioning the Destination SQL Azure Database
Task 2 – Generating a DDL Script
Task 3 – Executing the DDL Script against SQL Azure
Task 4 – Creating Migration Assistant Stored Procedures
Task 5 – Disabling Foreign Key Constraints
Task 6 – Disabling non-clustered Indexes
Task 7 – Using bcp to Export Table Data from your Source SQL Server Database
Task 8 – Using bcp to Import Table Data into your Destination SQL Azure Database
Task 9 – Rebuilding non-clustered Indexes
Task 10 – Enabling Foreign Key Constraints
Summary
Overview
SQLAzureDatabaseisbasedonMicrosoftSQLServer,whichmakesitrelativelyeasytomoveexistingSQLServerdatabasestoSQLAzure.Inthishands-onlab,youwilllearnhowtomoveaschemaanddatatoSQLAzurebyusingbruteforceScriptswithBCPcommand-linetooltocopydataintoandoutofSQLAzure.
Objectives
Inthishands-onlab,youwilllearnhowto:
- UseSQLAzureasacloudhosteddatabaseplatformforyourapplications.
- Youwilllearnhowto
◦Migrateanexistingdatabase(schemadata)
Prerequisites
Thefollowingisrequiredtocompletethishands-onlab:
- SQLServerManagementStudio2008R2ExpressEdition
Exercises
Thishands-onlabincludesthefollowingexercises:
- Exercise 1: Moving an Existing Database to the Cloud
Estimatedtimetocompletethislab:30minutes.
Exercise1:MovinganExistingDatabasetotheCloud
Inthisexercise,youwillmoveanexistingon-premisesdatabasefromSQLServertothecloud.Youwilldothisbyusingthebruteforceapproach,usingscripts.
Task1–ProvisioningtheDestinationSQLAzureDatabase
InthisstepyouwillprovisionanemptySQLAzuredatabasethatyouwillusetomigratealloftheAdventureWorksDW2008R2databaseobjectscontainedinyourlocalSQLServerinstance.
- Navigate and signintotheWindows Azure Management PortalDatabaselink in the left paneandselecttheProjectNameassociatedwithyourSQLAzuresubscription.
- From the Server List, select the server you are going to use to perform the Lab and takenoteoftheinformationinthePropertiessection,including:
Fully Qualified DNS name(e.g.myserver.database.windows.net)
AdministratorLogin(e.g.mysqladminuser) - IntheRibbonmenu,clickCreate.
Figure1
CreateDatabase
- Enterthefollowinginformation:
- Database name:AdventureWorksDW2008R2
- Edition:Web
- Maximum size:1GB
Note:Rightnow,themaindifferencebetweenWebandBusinessdatabaseeditionsisstorageandprice.Webeditiondatabasescanbeprovisionedforupto5GBofrelationalstorage.Businesseditiondatabasescanbeprovisionedforupto50GBofrelationalstorage.Webeditionissignificantlylessexpensiveforpaidsubscriptions.AsSQLAzureevolves,“enterprise”featureswillmostlikelybemonetizedbyrequiringBusinessedition.
Figure2
CreateDatabase
- ClickOK.
- ClickFirewallRulesbutton,andcheckthe“AllowotherWindowsAzureservicestoaccessthisserver”option.ThiswillallowotherservicesrunningintheAzureServicesenvironmenttointeroperatewithyourSQLAzureserver.
Figure3
FirewallRules
- Now,clicktheAddbutton,andenterthecorrectIPaddressrangetograntaccesstotheIPaddressesyouwillusetoconnecttoSQLAzure,forexample:
Rule name:GrantAccessToAllAddresses
IPrange start:0.0.0.0
IPrange end:255.255.255.255
Figure4
FirewallRules–AddFirewallRule
Note:TheexampleshownheregrantsaccesstoallIPaddresses.GrantaccessonlytotheIPaddressesyouactuallyneedtoavoidunauthorizedusage.
Task2–GeneratingaDDLScript
InthisstepyouwillgenerateaDDLscriptcapableofrecreatingalloftheobjectsinyoursourcedatabase.DDLstandsfor“DataDefinitionLanguage”whichisshorthandforthevariousTransact-SQLcommandsusedtocreatedatabaseobjectssuchastables,viewsandstoredprocedures.
- LaunchSQLServerManagementStudio.
- ConnecttotheSQLServerinstancethatyouinstalledtheAdventureWorksDW2008R2databaseon.
- ExpandtheDatabasesnodeinObjectExplorer,right-clickAdventureWorksDW2008R2andselectTasksGenerateScripts.
- IfthereappearsanIntroductiondialog,clickNext.
- IntheChooseObjectsdialog,choosethe“Selectspecificdatabaseobjects”option,thenchecktheTables,ViewsandUser-DefinedFunctionsoptions.
Figure5
GenerateScripts–ChooseObjects
Note:AdventureWorksDW2008R2containsaDDLTrigger.SQLAzuredoesnotcurrentlysupportDDLTriggerssodonotselectthisoption.
- ExpandtheTablesnodeanduncheckthefollowingtables:
- AdventureWorksDWBuildVersion
- DatabaseLog
- FactFinance
Figure6
GenerateScripts–ChooseObjects
Note:SQLAzurerequiresalltablestohaveaclusteredindex.Thesetablesdonothaveclusteredindexes,andtheyarenotessentialforthisparticularsampledatabase.
- IntheChooseObjectsdialog,clickNext.
- IntheSetScriptingOptionsdialog,clicktheAdvancedbuttonandmakethefollowingchanges,thenclickOK:
Figure7
GenerateScripts–ChooseObjects
- SettheGeneral“Scriptforthedatabaseenginetype”optionto“SQLAzureDatabase”
- SettheTable/ViewOptionsScriptIndexesoptiontoTrue
Figure8
GenerateScripts–ChooseObjects
- IntheSetScriptingOptionsdialog,settheoutputtypeto“Savescriptstoaspecificlocation”,andchoosethe“Savetonewquerywindow”option,thenclickNext.
Figure9
GenerateScripts–SetScriptingOptions
- ReviewtheinformationintheSummarydialog,thenclickNext.Atthispointthewizardwillinterrogatetheschemaofthesourcedatabaseandgenerateascripttorebuildalloftheobjectsinthedatabaseintoanewquerywindow.
- ReviewtheinformationintheSaveorPublishScriptsdialogthenclickFinish.
Figure10
GenerateScripts–SaveorPublishScripts
- ReturntoSQLServerManagementStudioandreviewthescriptthatwasgenerated.
Task3–ExecutingtheDDLScriptagainstSQLAzure
InthisstepyouwillexecutetheDDLScriptyouhave generatedagainsttheAdventureWorksDW2008R2databaseyouprovisionedinSQLAzure.Oncecompleted,allofthetables,views,storedproceduresandotherobjectsfromyoursourcedatabasewillexistinyournewlyprovisionedSQLAzuredatabase.Atthispointtherewillbenodatainthetables.
- Right-clickthequerywindowandselectConnectionChangeConnection.
Figure11
GenerateScripts–ChooseObjects
- ThiswillbringuptheConnecttoDatabaseEnginedialogsoyoucanconnecttoyournewlycreatedAdventureWorksDW2008R2databaseinSQLAzure.Entertheconnectioninformationyounotedearlier,forexample:
- Servername:[myserver.database.windows.net]
- Authentication:SQLServerAuthentication
- Login:[mysqladminuser@myserver]
- Password:[mysqladminuserpassword]
Figure12
ChangeConnection
Note:YoucanselecttheRememberPasswordoptiontoavoidhavingtoretypeyourpasswordeachtimeyouconnect
- ClickConnect.
- ChangetheactivedatabasetoAdventureWorksDW2008R2usingtheAvailableDatabasesdrop-downlistboxinthetoolbar.
Note:Alwayscheckyourcurrentdatabasecontextbeforerunningascripttoavoidmakingchangestothewrongdatabase.
Figure13
ChangeConnection
- ExecutethequerybypressingF5orbyselectingtheQueryExecutemenuoption.
- Reviewthestatusinformationatthebottomofthequerywindowandverifythatthequeryexecutedsuccessfully.
- UsingObjectExplorer,connecttoyourSQLAzureserverwiththeappropriatecredentials.ExpandtheDatabasesnode,thenexpandtheTablesnode inside AdventureWorksDW2008R2 database.ReviewthetablesthatwerecreatedandcomparethemtothoseinyourlocalSQLServerinstance.
Figure14
Reviewgeneratedtables
Task4–CreatingMigrationAssistantStoredProcedures
InthisstepyouwillcreatetwostoredproceduresintheSQLAzureAdventureWorksDW2008R2databasethatwillsimplifytheprocessofmigratingyourdata.
TheSetForeignKeyEnabledStatusstoredprocedurewillbeusedtodisableforeignkeyconstraintsduringdatamigration.Thiswillpermityoutoloadyourtablesinwhateverorderisconvenientwithoutregardtoprimarykey/foreignkeyrelationships.Youwillrunthisstoredprocedureagainwhendatamigrationiscompletetore-enablealloftheforeignkeyconstraints.
TheSetIndexEnabledStatusstoredprocedurewillbeusedtodisableallnon-clusteredindexesduringdatamigration.Thisspeedsupthedataloadingprocess.Youwillrunthisstoredprocedureagainwhendatamigrationiscompletetorebuildallofthenon-clusteredindexes.
Usethefollowingproceduretocreatethestoredprocedures.ThesourcecodefortheCreateMigrationAssistantProcedures.sqlTransact-SQLscriptfilereferencedintheinstructionsisincludedattheendofthissection.Toexecutethescript,youwillusethesqlcmdutility,whichisauseful command-promptutilityforperformingbatchoperationsagainstSQLServerandSQLAzure.
- Openacommandpromptandchangethecurrentdirectorytothe[labPath]\Assetsfolder.
- ExecutethefollowingcommandusingtheappropriateconnectiondetailsforyourSQLAzureserver:
CommandPrompt
-b
Note:The–bparameterensuresthatsqlcmdwillreturnanon-zeroerrorcodeifanerroroccurswhenrunningascript.Thiscanbeusedtoterminateabatchfileifanerroroccurs.
- LaunchSQLServerManagementStudio,connecttoyourSQLAzureserver,andexpandtheDatabasesAdventureWorksDW2008R2ProgrammabilityStoredProceduresnode.VerifythattheSetForeignKeyEnabledStatusandSetIndexEnabledStatusstoredproceduresareinthelist.
Figure15
Reviewgeneratedstoredprocedures
Thesetwostoredproceduresiteratethroughobjects(foreignkeysandindexes)insystemcatalogviews.Foreachiteration,these objectsdynamicallyconstructaTransact-SQLcommandtoenableordisabletheobject,and thenthey executethedynamicallyconstructedcommand.
Task5–DisablingForeignKeyConstraints
InthisstepyouwillusetheSetForeignKeyEnabledStatusstoredprocedurecreatedintheprevioussteptodisablealloftheforeignkeyconstraintsintheAdventureWorksDW2008R2SQLAzuredatabase.Thiswillmakeiteasiertoloaddatabyremovingtheneedtodoitinaspecificordertoavoidviolatingforeignkeyconstraints.Youwillre-enabletheforeignkeyconstraintslaterafteryouarefinishedloadingyourdata.
Notethatbydefault,bcpwillbypassconstraintchecking,howeveritisstillusefultodothisifyouareusingothermechanismstoloadyourdata,suchasscriptfilesorsomeotherapplication.
- Openacommandprompt.
- ExecutethefollowingcommandusingtheappropriateconnectiondetailsforyourSQLAzureserver:
CommandPrompt
sqlcmd-Smyserver.database.windows.net-Umysqladminuser@myserver-Pmysqladminuserpassword-dAdventureWorksDW2008R2-Q"EXECUTE[dbo].[SetForeignKeyEnabledStatus]0" -b
Note:Usethe–Qparametertosendasinglecommandinsteadofexecutingascriptfile.
Task6–Disablingnon-clusteredIndexes
InthisstepyouwillusetheSetIndexEnabledStatusstoredprocedurecreatedpreviouslytodisableallofthenon-clusteredindexesintheAdventureWorksDW2008R2SQLAzuredatabase.Thiswillimprovetheperformanceofdataloadingbyavoidingincrementalindexrebuildsduringtheloadingprocess.Youwillre-buildthenon-clusteredindexeslaterafteryouarefinishedloadingyourdata.Notethatyouwillnotdisableclusteredindexessincethedataisloadedinclusteredindexorder,andSQLAzurerequiresclusteredindexesonalltables.
- Openacommandprompt.
- ExecutethefollowingcommandusingtheappropriateconnectiondetailsforyourSQLAzureserver:
CommandPrompt
sqlcmd-Smyserver.database.windows.net-Umysqladminuser@myserver-Pmysqladminuserpassword-dAdventureWorksDW2008R2-Q"EXECUTE[dbo].[SetIndexEnabledStatus]0" -b
Task7–UsingbcptoExportTableDatafromyourSourceSQLServerDatabase
Inthisstepyouwillusethebcp(bulkcopyprogram)command-lineutilitytoexportdatafromyoursourceSQLServerdatabase.Whenyoucompletethisstep,youshouldhaveone“native”fileforeachofthetables.
- OpentheExportTableData.cmdfilefromthe[labPath]\Assetsfolder.
- Replacethefollowingvariablesatthebeginningofthedocumentwiththeappropriatevalues:
- SourceSqlServerName:LocalSQLServername
- SourceSqlDbName:LocalSQLServerdatabasename
Figure16
ExportTableData-Replacescript’svariables
- ClosetheExportTableData.cmdfile.
- Openacommandpromptandchangethecurrentdirectorytothe[labPath]\Assetsfolder.
- ExecutetheExportTableData.cmdscript.
Internallythescriptwillexecutethefollowingcommandonceforeachtable:
CommandPrompt
bcpdbo.MyTableNameoutMyTableName.dat-n-SMySqlServerName-T
Note:Usethe–nparametertousethe“native”fileformatforexport. Thenativeformatimprovesperformanceonimportbyavoidingunnecessaryconversions.Usethe–TparametertoconnecttoSQLServerusingyourWindowscredentials.
- Examinetheoutputandverifythatthefileswerecreated.
Task8–UsingbcptoImportTableDataintoyourDestinationSQLAzureDatabase
Inthisstepyouwillusethebcpcommand-lineutilitytoimportdatafroma“native”fileintoyourdestinationSQLAzuredatabase.Whenyoucompletethisstep,allofyourdatashouldbeloaded.
- OpentheImportTableData.cmdfilefromthe[labPath]\Assetsfolder.
- Replacethefollowingvariablesatthebeginningofthedocumentwiththeappropriatevalues:
- DestSqlServerName:[myserver.database.windows.net]
- DestSqlDbName:SQLAzureServerdatabasename
- DestSqlUserName:[mysqladminuser@myserver]
- DestSqlUserPassword:SQLAzureAccountLoginpassword
Figure17
ImportTableData-Replacescript’svariables
- ClosetheImportTableData.cmdfile.
- Openacommandpromptandchangethecurrentdirectorytothe[labPath]\Assetsfolder.
- ExecutetheImportTableData.cmdscript.
Internallythescriptwillexecutethefollowingcommandonceforeachtable::
CommandPrompt
bcpdbo.MyTableNameinMyTableName.dat-n-Smyserver.database.windows.net-Umysqladminuser@myserver-Pmysqladminuserpassword-E
Note:Bcpisverypickyaboutparameterformats.Donotuseaspaceafterthe–Uand–Pparameters.
Note:BecarefulwhenimportingdataintocolumnsthatusetheIDENTITYproperty. Usethe–EparametertousevaluesinthedatafileforIDENTITYcolumnsinsteadofgeneratingnewidentityvaluesduringimport.Ifyoudo notdothisyouriskbreakingforeignkeyrelationships.
- Examinetheoutputtoensurethatalldatawassuccessfullycopiedintothedestinationtable.
Task9–Rebuildingnon-clusteredIndexes
InthisstepyouwillusetheSetIndexEnabledStatusstoredproceduretorebuildthenon-clusteredindexesyoudisabledinstep6.It’sbesttodothisinoneshotafterloadingallofyourdata.
- Openacommandprompt.
- ExecutethefollowingcommandusingtheappropriateconnectiondetailsforyourSQLAzureserver:
CommandPrompt
sqlcmd-Smyserver.database.windows.net-Umysqladminuser@myserver-Pmysqladminuserpassword-dAdventureWorksDW2008R2-Q"EXECUTE[dbo].[SetIndexEnabledStatus]1"-b
Task10–EnablingForeignKeyConstraints
InthisstepyouwillusetheSetForeignKeyEnabledStatusstoredproceduretoenabletheforeignkeyconstraintsyoudisabledinstep5.
- Openacommandprompt.
- ExecutethefollowingcommandusingtheappropriateconnectiondetailsforyourSQLAzureserver:
CommandPrompt
sqlcmd-Smyserver.database.windows.net-Umysqladminuser@myserver-Pmysqladminuserpassword-dAdventureWorksDW2008R2-Q"EXECUTE[dbo].[SetForeignKeyEnabledStatus]1"-b
Summary
WhenworkinghandsonwithSQLAzuremigrating,existingSQLServerdatabasesisoneofthefirstthingscustomersexperimentwith.Inthisexercise,youworkedhandsonwiththebruteforceapproach.