Author: Calin OPREA

  • AdventureWorks2025 to an Azure SQL VM, part 6: check post-migration, and clean up

    Part 6 of 6. The series: 1. The plan and the lab · 2. Check what is there · 3. Export what the target needs · 4. Back up and upload · 5. Restore · 6. Check post-migration, and clean up (this post).

    Part 5 ended with AdventureWorks2025 ONLINE on the VM, encrypted with the laptop’s certificate, and its login back with the laptop’s SID. ONLINE is not the same as “the same database”, though. This post is where you prove it: one script, 50, holds the restored database against the facts the laptop wrote right after its last backup, in D2 of part 4.

    Then the clean-up, because a lab left running is a bill: 99 puts the machines back as they were, 00 takes the Azure base down, and then the free account itself, which takes more steps (and more days) than I expected.

    Part G. Check post-migration, and clean up

    G1. The post-migration check: script 50

    50_PostRestore-Check.ps1 runs on the VM. With the VM’s identity, as 40 and 41 did, it downloads the newest facts file the laptop uploaded (facts/<laptop>/AdventureWorks2025/ in the backups container), then works through it:

    1. The backup. The database here comes from the laptop’s last backup (the same last LSN as in the facts), and the laptop had no user writes after that backup. If it had, the row counts and checksums below can differ for that reason alone, and 50 says so. This is why the facts are taken after the last LOG backup, not after a tail-log (part 4).
    2. The owner, the only thing 50 changes. On the laptop the owner was a Windows login of the laptop, which cannot exist on the VM, so after the restore the owner is whoever ran it. 50 sets it to sa, or to the login you pass with -Owner.
    3. The settings of the database, one by one, against the laptop’s.
    4. DBCC CHECKDB, unless you pass -SkipCheckDb (for a database big enough that you check it another way).
    5. The tables: the same tables, the exact row count of each, and a checksum of the data of each.
    6. The objects and the code: the objects by type (tables, views, procedures, constraints, indexes and the rest), and one hash over the code of every module, so a procedure changed by a single character shows.
    7. TDE: the database is encrypted with the laptop’s certificate (same thumbprint).
    8. Reported, not changed: the SQL logins as on the laptop (SID, default database, policy, server roles), database users without a login, full-text indexes when Full-Text Search is not installed on the VM, and SQL Agent jobs on the laptop that name the database. Those are decisions for you; 50 lists them and leaves them alone.

    [VM, PowerShell as administrator] As a Windows login that is sysadmin in SQL Server. -SourceServer is your laptop’s name, as in part 5:

    .\50_PostRestore-Check.ps1 -StorageAccount aw2025mig12345 -SourceServer <your laptop's name> -WhatIf
    .\50_PostRestore-Check.ps1 -StorageAccount aw2025mig12345 -SourceServer <your laptop's name>

    Here -WhatIf runs every check and only leaves the owner as it is. So read the -WhatIf first: if anything other than the owner is off, stop there and find out why before the real run.

    Mine, in the -WhatIf: the same last LSN, no writes on the laptop after it, 18 settings the same, CHECKDB clean in 2 seconds, 71 tables and 760,174 rows with the same counts and checksums, the objects by type the same, 51 modules with the same hash, the same TDE certificate, the login the same, no users without a login, Full-Text Search installed (the database has three full-text indexes), and no jobs. Only the owner was left, and the real run set it to sa.

    What 50 cannot tell you: whether the applications connect, and whether the database runs as fast as it did. Those are tests for the application, not for the database.

    Expected: a CHECK table of 15 lines, all OK, then All OK. AdventureWorks2025 on <VM> matches <your laptop's name>.

    G2. Clean up: scripts 99 and 00

    There are two ways out of the lab, and they share the first step:

    • To run it all again (what I did on 13 Nov, to redo the series end to end): 99 on both machines, then 00 and 01 in Cloud Shell for an empty Azure base, and start again from 10.
    • To take it all down: 99 on the laptop, then delete the resource group. The VM goes with it, so 99 on the VM is not needed.

    99_Reset-Lab.ps1 puts one machine back as it was before the migration. It is for the lab only: it decrypts and changes the source database, drops the target database and deletes files. So it asks you to type the machine’s name before it changes anything.

    -SideWhat 99 undoesWhat it keeps
    Source (the laptop)TDE off (decrypted, then the encryption key dropped), recovery model back to SIMPLE, the certificate AW2025_TDE (only if no database uses it), the master key in master (only if nothing else in master needs it), the key files, and the backup, facts and inventory foldersthe database, its users and the SQL logins (they are what the migration moves), the backup history in msdb
    Target (the VM)the database, the SQL logins in -Logins, the certificate and the master key in master (same rules), the staging folder F:\Restorethe authentication mode, SQL Server’s settings

    [laptop, PowerShell as administrator] As a Windows login that is sysadmin in SQL Server:

    .\99_Reset-Lab.ps1 -Side Source -WhatIf
    .\99_Reset-Lab.ps1 -Side Source

    [VM, PowerShell as administrator] Only if you are going to run the series again:

    .\99_Reset-Lab.ps1 -Side Target -WhatIf
    .\99_Reset-Lab.ps1 -Side Target

    In a real migration, this is the step you skip. 99 drops the certificate and deletes its key files, and 00 (or the resource group’s deletion) takes the password with the vault. After that, nothing can read a backup encrypted with that certificate. In the lab that is the point. In real life the certificate, its private key and its password are kept for as long as any backup encrypted with it is kept.

    00_Remove-AzureLabBase.ps1 removes what 01 created in part 1: the role assignments, the Key Vault (deleted and purged, so its name can be used again), the storage account with every blob in it, and the VM’s managed identity. It keeps the resource group and the VM. Nothing it does can be undone, so it lists what would go and asks you to type the resource group’s name first.

    [Cloud Shell, PowerShell] Signed in to the lab subscription:

    ./00_Remove-AzureLabBase.ps1 -StorageAccount aw2025mig12345 -KeyVault aw2025-kv-1234 -WhatIf
    ./00_Remove-AzureLabBase.ps1 -StorageAccount aw2025mig12345 -KeyVault aw2025-kv-1234

    To take everything down, delete the resource group instead: in the portal, or in Cloud Shell:

    Remove-AzResourceGroup -Name AW2025Migration

    The vault goes with the group, but only into soft delete: its name stays taken for 90 days unless you purge it too:

    Get-AzKeyVault -InRemovedState
    Remove-AzKeyVault -VaultName aw2025-kv-1234 -Location <the vault's region> -InRemovedState

    Mine, on 13 Nov: 99 -Side Source on the laptop (TDE off, SIMPLE, the certificate and the master key dropped, the key files, backups and inventory deleted; the database, its user and the login kept). Then the resource group deleted, with the VM, its three disks, the network, the SQL virtual machine resource, the extensions, the storage account and the vault, and the vault purged. All that was left was NetworkWatcherRG, empty: Azure creates it on its own with the first virtual network in a region.

    Expected: for 99, a CHECK table all OK (on the laptop: the database ONLINE and not encrypted, in SIMPLE, the certificate gone, the files deleted). For 00, a CHECK table of four lines, all OK: the storage account gone, the vault gone, no managed identity on the VM, the resource group kept.

    G3. Closing the free account

    The lab ran on an Azure free account, on an Outlook.com address made for it and nothing else (part 1). Deleting the resources stops the costs; it does not close the account. That takes four more steps, in this order, and the order is forced on you:

    1. Cancel the subscription. [portal] Subscriptions, the lab subscription, Cancel subscription. Billing stops at once. Check Cost Management first, so that nothing you forgot is still running.
    2. Wait three days, then delete it. The Delete subscription option only shows up three days after the cancel. If you never press it, Azure deletes the subscription itself 90 days after the cancel.
    3. Then remove the card. The portal will not let a card go while a subscription is tied to it, even a cancelled one. Delete the subscription first, check that the last invoice is 0, and then the card can be removed.
    4. Close the Microsoft account. [browser] account.live.com/closeaccount.aspx, signed in as the lab account. You choose a reopen window of 30 or 60 days; after it, the account and its data are deleted for good.

    Signing in reopens it. During the reopen window, signing in to the closed account is how you reopen it. So don’t sign in “just to check” once it is closed, and take the lab account off any browser, password manager or Cloud Shell session that might sign in on its own.

    Mine: subscription cancelled on 13 Nov, a few minutes after the resource group was gone. A week later it is still there, Disabled, with Delete available since 16 Nov. The whole lab cost €58.42, nearly all of it the VM (€43.64) and its two data disks (€6.80 each), and all of it came out of the free credit: the account was never upgraded to pay-as-you-go, so nothing went to the card, and €121.13 of the credit was left unused. The portal says the free account itself will be deleted on 10 January 2027. Deleting the subscription, removing the card and closing the account are still on my list.

    Expected: the subscription gone from Subscriptions, no card on the account, and a closure date from the closing page.

    Check the scripts before you run them

    The scripts of this post, from the v1.0 release (immutable: nobody, me included, can change its files or its tag). On the laptop and on the VM:

    Get-FileHash C:\AW2025Migration\scripts\50*.ps1, C:\AW2025Migration\scripts\99*.ps1 -Algorithm SHA256 | Format-Table Hash, Path -AutoSize

    In Cloud Shell, after the upload: Get-FileHash ./00_Remove-AzureLabBase.ps1.

    Every hash must match its line below; SHA256SUMS.txt on the release has all of them. If one differs, don’t run it.

    FileSHA-256
    aw2025-azure-migration-v1.0.zip0db411127783f4f2c604211d8293b2854a7776b0289d54b57344890e73c45d4f
    00_Remove-AzureLabBase.ps161fe8c80e1836b8f5a43ff1af6e71c9a891e79e73881bf0fa0427a1aa914e644
    50_PostRestore-Check.ps1d4bcab3967355383fd607f4c665d39a15d9c387f07f16cb1233257978324069a
    99_Reset-Lab.ps102817baa5c5a0c875ec6e3943861f93fbe5944837ed5b99fe14760ef29b903b3

    Looking back

    Six posts, fourteen scripts, one database. Every script has a -WhatIf if it changes anything, every one ends with a table of what is OK and what is not (the CHECK table, or the gates of 12), and every step of the run is in these posts with what I got. The order did most of the work: look before you change anything, export what the target cannot get any other way (the certificate, the logins), take the facts right after the last backup, and prove the result against those facts instead of trusting that ONLINE means done.

    What I would add before using this for a real database:

    • A tail-log cutover. v1.0 ends with a normal LOG backup, so the facts can still be read from the source (part 4). A real cutover ends with a tail-log WITH NORECOVERY, and the facts have to come before it.
    • Tighter storage. The key files in a container of their own, where the VM can only read; soft delete on blobs and containers; a storage firewall that lets in only the source and the VM’s network.
    • The source on the latest CU, before the first backup, not after.
    • The VM stopped (deallocated) between sessions. A SQL Server VM with a pay-as-you-go licence pays for the licence by the hour while it runs.

    Of course, the true power of the runbook is once you can automate it, but that is another story for another time.

    Thank you for reading all six. If you run it, I would like to know where it broke for you.

    The scripts are on GitHub: calinsqlplay/aw2025-azure-migration (the version these posts use is the v1.0 release).

  • AdventureWorks2025 to an Azure SQL VM, part 5: restore

    Part 5 of 6. The series: 1. The plan and the lab · 2. Check what is there · 3. Export what the target needs · 4. Back up and upload · 5. Restore (this post) · 6. Check post-migration, and clean up.

    Part 4 left everything the VM needs in one place: the backups, the facts, the key files and the inventory in Blob storage, the passwords and the logins in Key Vault. From here on the laptop is out of the picture, and every step runs on the VM.

    None of it needs the Az module or a sign-in. The VM asks Azure’s metadata endpoint for a token, as its own managed identity, and uses that token against Blob storage and Key Vault directly (the roles from A3 in part 1). No key, password or certificate for Azure is ever stored on the VM.

    Two scripts, in this order: 40 brings the database back, 41 brings back the login it needs.

    Part F. Restore

    F1. Restore from Blob: script 40

    40_Restore-FromBlob.ps1 does five things, and the order is the whole point:

    1. Checks that it is not on the laptop, that it runs as an administrator who is sysadmin, and that the VM’s identity reaches both Blob storage and Key Vault.
    2. Downloads the backups (<laptop>/AdventureWorks2025/FULL/ and /LOG/) and the key files (keys/<laptop>/) to a staging folder, F:\Restore. A file already there is skipped.
    3. Installs the TDE certificate, if the VM has none with the backup’s thumbprint: first a database master key in master, with a password generated and used once, then AW2025_TDE from the .cer and .pvk, with the password read from Key Vault (aw2025-pvk-password). The key files are deleted from the staging folder straight after.
    4. Restores the newest FULL WITH NORECOVERY, to the VM’s default data and log folders, then every LOG after it, in order. A log already applied is skipped; a gap in the chain stops the script, with nothing lost: put the missing file in Blob and run it again.
    5. Recovers the database, and ends with the CHECK table.

    [VM, PowerShell as administrator] As a Windows login that is sysadmin in SQL Server. -SourceServer is your laptop’s name, as in B4:

    .\40_Restore-FromBlob.ps1 -StorageAccount aw2025mig12345 -KeyVault aw2025-kv-1234 -SourceServer <your laptop's name> -WhatIf
    .\40_Restore-FromBlob.ps1 -StorageAccount aw2025mig12345 -KeyVault aw2025-kv-1234 -SourceServer <your laptop's name>

    Two switches for the real thing:

    • -NoRecovery leaves the database RESTORING. Restore the FULL days before the cutover, then run 40 again after the last LOG is in Blob: it carries on from where it stopped and applies only what is new.
    • -Replace restores over an ONLINE database of the same name on the VM, and asks you to type the name first. Without it, 40 refuses to touch an existing database.

    The certificate comes first, even to read the file list. My first run stopped before restoring anything: RESTORE FILELISTONLY failed with Cannot find server certificate with thumbprint …. I had expected the certificate to matter for the restore itself, not for reading which files are in the backup. On SQL Server 2025 it matters for both. So 40 installs the certificate before it opens the backup at all, and then compares the thumbprint inside the backup with the certificate it has just installed.

    Mine downloaded four files (the FULL, the LOG and the two key files), created the master key, installed AW2025_TDE, restored the FULL and one LOG, and brought AdventureWorks2025 ONLINE and encrypted, at the laptop’s time of the last LOG backup.

    Expected: a CHECK table of four lines, all OK: the database ONLINE (or RESTORING with -NoRecovery), encrypted with the laptop’s certificate, restored from the laptop’s backups, and the key files gone from the staging folder. Then All OK. AdventureWorks2025 is ONLINE on <VM>. Next: 41_Import-Logins.ps1.

    F2. The SQL logins: script 41

    The database is back, and so is its user. The login that user belongs to is still only in Key Vault, in the secret aw2025-logins from C2 in part 3. 41_Import-Logins.ps1 reads it with the VM’s identity and, for each SQL login in it:

    On the VMWhat 41 does
    missingCREATE LOGIN ... WITH PASSWORD = <hash> HASHED, SID = <sid>, with the laptop’s default database and language, password policy and expiration flags; disabled if it was disabled there
    there, with the same SIDleaves it as it is
    there, with another SIDreports it and changes nothing: its user would not map. Drop it and run again, or fix the user yourself

    Then it adds the server roles and server-level permissions the login had on the laptop (it adds, never removes), and lists the database’s users with the login each one maps to.
    Just a side note: as previously said, this is the part that worked only partly for me (custom permissions), so keep an eye on this.

    [VM, PowerShell as administrator] As a Windows login that is sysadmin in SQL Server:

    .\41_Import-Logins.ps1 -KeyVault aw2025-kv-1234 -SourceServer <your laptop's name> -WhatIf
    .\41_Import-Logins.ps1 -KeyVault aw2025-kv-1234 -SourceServer <your laptop's name>

    If you skipped the G7 fix by hand in part 2, -EnableSqlAuth does it here: it switches the server to SQL Server and Windows authentication and restarts SQL Server and Agent.
    Back in the 2020 era I would have said that it is mandatory to have mixed mode authentication, but right now I am not so sure about it anymore – Microsoft is pushing hard to a cloud-only, Entra-based architecture, which is meant to change the security game. We will see how this goes, though.

    Prove the password, not just the login. A login with the right SID maps the user; it does not prove the password came across. For that, put one login’s password in Key Vault as aw2025-login-<login name in lower case>-password, and 41 signs in as that login and checks it lands in the database as its user. I skipped it in the lab, so the line for it says 0 tested.

    Mine created AW2025Migration with the laptop’s SID and password hash, and the user in AdventureWorks2025 mapped to it on its own: no ALTER USER, no orphaned users, no fix-up script.

    Expected: a CHECK table of six lines, all OK: every SQL login is there with the laptop’s SID, every one maps to its user, no SQL users without a login, SQL logins can sign in (authentication mode), the sign-in test passed for every login tested, and no Windows logins to decide on. Then All OK. 1 login(s) created. Next: 50_PostRestore-Check.ps1.

    Check the scripts before you run them

    The scripts of this post, from the v1.0 release (immutable: nobody, me included, can change its files or its tag). On the VM:

    Get-FileHash C:\AW2025Migration\scripts\4*.ps1 -Algorithm SHA256 | Format-Table Hash, Path -AutoSize

    Every hash must match its line below; SHA256SUMS.txt on the release has all of them. If one differs, don’t run it.

    FileSHA-256
    aw2025-azure-migration-v1.0.zip0db411127783f4f2c604211d8293b2854a7776b0289d54b57344890e73c45d4f
    40_Restore-FromBlob.ps111578b5f373a572c14a2e855f3772c8d176cd2c1a2631120ac9ff7c52a4c2acf
    41_Import-Logins.ps1d3f4641a9101635d11dee994dc48c8b7ec54c88ef77e1832b508f6b8720b3bc0

    Next

    Part 6 is part G, the last one: script 50 holds the restored database against the facts from part D (settings, row counts and checksums, objects, the hash of the code, users and logins), runs CHECKDB and sets the owner. Then the clean-up: 99 resets the lab, 00 takes Azure down (with a vault purge that is slower than it says), and the bits nobody tells you about closing a free account.

    The scripts are on GitHub: calinsqlplay/aw2025-azure-migration (the version these posts use is the v1.0 release).

  • AdventureWorks2025 to an Azure SQL VM, part 4: back up and upload

    Part 4 of 6. The series: 1. The plan and the lab · 2. Check what is there · 3. Export what the target needs · 4. Back up and upload (this post) · 5. Restore · 6. Check post-migration, and clean up.

    Part 3 left the laptop with AdventureWorks2025 encrypted (and the laptop in service, that CPU can go to higher temperatures than the surface of the Sun), in FULL recovery, its certificate backed up and proved, and its SQL login safe in Key Vault. Now the data itself moves: part D backs it up and writes down what it looked like at that moment, part E carries it all to Azure.

    In a real migration this is where the cutover lives, so the order matters:

    1. Days before: a FULL backup, uploaded at leisure. On a big database this is the slow part, and it happens while the application still runs.
    2. At cutover: the application stops. One last LOG backup, taken after nobody can write any more.
      Side note here: I am usually doing tail-LOG backups so the databases stay in Restoring. This has two benefits: no one can touch any database, and you have the basis for the restore in case you need to roll back.
      However, this is just a demo, so not everything applies.
    3. Right after it: the facts of the database, as it was at that last backup (row counts, checksums, objects). Part G holds the VM against them.
      With a tail-log backup instead, take the facts just before it.
    4. Then the upload of whatever is not in Azure yet: the last log, the facts, and anything missed.

    The downtime is steps 2 to 4 plus the restore of the logs on the VM, not the size of the database. In the lab I did all four in one go, a few minutes apart: AdventureWorks2025 is 55 MB as a backup, and nobody was waiting for it.

    Part D. Back up

    D1. FULL and LOG backups: script 30

    30_Backup-Source.ps1 takes the backups to a local folder; the upload is a separate step (E1), so a slow line never holds a backup open. Every backup is:

    • checksummed and compressed (WITH CHECKSUM, COMPRESSION), with a 4 MB transfer size;
    • verified straight after it is written (RESTORE VERIFYONLY ... WITH CHECKSUM);
    • named the way Ola Hallengren’s jobs name them: <server>_<database>_FULL_yyyyMMdd_HHmmss.bak and ..._LOG_....trn, in D:\Backups\<laptop>\AdventureWorks2025\FULL\ and \LOG\. The time in the name is the laptop’s local time, and the restore in part F reads it: that is why the VM’s time zone had to match, back in part 1.
      I have to stop here for a bit: LRS work a tad differently when it comes with the folder and subfolder structures, so be mindful of that.

    Nothing is ever deleted, and every run only adds backups. Before the first backup, the script gives the SQL Server service Modify on D:\Backups, since the service is the one that writes the files.

    [laptop, PowerShell as administrator] As a Windows login that is sysadmin in SQL Server. No Azure sign-in is needed here:

    .\30_Backup-Source.ps1 -WhatIf
    .\30_Backup-Source.ps1

    The default is a FULL, then a LOG. At cutover, after the application stops, the last one is a LOG on its own:

    .\30_Backup-Source.ps1 -Type Log

    It refuses a LOG backup while there is no log chain yet: after the switch to FULL recovery in part C, the chain starts with the first FULL.

    TDE and compression. For years, compressing a backup of a TDE database gained nothing: encrypted pages do not compress. Since SQL Server 2016 they do, as long as the transfer size is above 64 KB, which is why 30 sets MAXTRANSFERSIZE = 4194304. On SQL Server 2016, 2017 and 2019 before CU5, leave it out and you will wonder why your compressed backup is as big as the database. Since SQL Server 2019 CU5 (I could have sworn is SQL 2022, but turns out it was earlier), the larger transfer size is no longer needed for TDE databases. Do your own testing here – for me it was 91 GB for a FULL backup against a 520+ GB database with Ola’s default backup settings.

    Mine: a FULL of 55.1 MB in 4 seconds and a tiny LOG, both verified.

    Expected: a CHECK table of two lines, all OK: this run’s backups were written and verified, and there is a FULL in the folder. Then All OK. Next: 31_Export-SourceFacts.ps1 (right after the last backup), then 32_Upload-ToBlob.ps1.

    D2. The facts, right after the last backup: script 31

    How do you know the database on the VM is the database, and not a database that happens to have the same name? You compare it with what the laptop’s database looked like at the moment of the last backup. 31_Export-SourceFacts.ps1 writes that moment down, read-only, in a small JSON file:

    • the settings: collation, compatibility level, recovery model, page verify, isolation options, trustworthy and the rest, plus the owner;
    • the last backup: its name, finish time and last LSN, and whether any user wrote to the database after it;
    • every user table: its exact row count (COUNT_BIG) and a checksum of its data (CHECKSUM_AGG(BINARY_CHECKSUM(*)));
    • the objects, by type: tables, views, procedures, functions, triggers, constraints, indexes, types, full-text indexes;
    • the code: a SHA-256 hash of every view, procedure, function and trigger;
    • users and logins: each user, the login it maps to, its SID and server roles (no password hashes: those are in Key Vault, from 21); SQL Agent jobs that name the database; the TDE certificate’s thumbprint.

    The file goes to D:\Backups\<laptop>\AdventureWorks2025\FACTS\; 32 uploads it in E1, and 50 reads it on the VM in part G.

    [laptop, PowerShell as administrator] Right after the last backup, and before anybody can write again:

    .\31_Export-SourceFacts.ps1 -WhatIf
    .\31_Export-SourceFacts.ps1

    Writes after the backup. If anything wrote to the database after the last backup, the row counts will not match on the VM, and part G will tell you so loudly. 31 checks for it (the last user update SQL Server saw, against the finish time of the last backup) and warns you. The fix is the cutover order from the top of this post: stop the application, 30 -Type Log, then 31.

    Mine, two minutes after the LOG backup: no writes after it; 71 tables with 760,174 rows between them; 89 CHECK constraints, 152 defaults, 90 foreign keys, 71 primary keys, 175 indexes, 20 views, 10 procedures, 11 functions, 10 triggers, 3 full-text indexes; and 51 modules of code, hashed.
    This is where I should stop and tell you that no, don’t do that. Simply create a table with 1 column and 1 value just before the tail-LOG backup and you will be fine. Having said that, do whatever suits you.

    Expected: a CHECK table of two lines, all OK: the facts file written, and no user writes after the last backup. Then All OK. Next: 32_Upload-ToBlob.ps1.

    Part E. Upload

    E1. Upload to Blob storage: script 32

    32_Upload-ToBlob.ps1 carries everything the VM needs from the laptop into the container, with the layout from Part 0 of part 1:

    On the laptopIn the container backups
    D:\Backups\<laptop>\AdventureWorks2025\FULL\*.bak and \LOG\*.trn<laptop>/AdventureWorks2025/FULL/ and /LOG/
    D:\Backups\<laptop>\AdventureWorks2025\FACTS\*.jsonfacts/<laptop>/AdventureWorks2025/
    D:\TDE-Keys\AW2025_TDE.cer and .pvkkeys/<laptop>/
    D:\Backups\<laptop>\INVENTORY\*.jsoninventory/<laptop>/ (if 10 did not upload it already)

    Passwords, password hashes and logins are not files: they went straight to Key Vault in part C, and they do not travel this way.

    A file that is already in Blob with the same size is skipped, and nothing is ever deleted, locally or in Blob. So it is safe to run it after the FULL days before the cutover, and again after the last LOG: the second run uploads only what is new.

    [laptop, PowerShell as administrator] Elevated, because the key folder is locked to Administrators (C1), and signed in to Azure (B1):

    .\32_Upload-ToBlob.ps1 -StorageAccount aw2025mig12345 -WhatIf
    .\32_Upload-ToBlob.ps1 -StorageAccount aw2025mig12345

    The laptop has no identity. The VM signs in to storage with its managed identity; the laptop cannot, because it is not in Azure. 32 reads the storage account key with your own Azure rights, for this run only, and never writes it anywhere. For a lab that is fine. For a real migration I would go further: give the upload its own identity with write rights on the container only, keep the key files in a separate container the VM can only read, and switch account-key access off once the move is done.

    Mine uploaded six files: the FULL, the LOG, the facts, the .cer, the .pvk, and an inventory from an earlier attempt (I am not supposed to tell you this, but not everything was unicorns and rainbows). All seven local files were then in Blob with the same size.

    Expected: a CHECK table of three lines, all OK: every local file is in Blob with the same size, the facts were taken after the last backup, and both TDE key files are in keys/<laptop>/. Then All OK. Next, on the Azure VM: 40_Restore-FromBlob.ps1.

    Check the scripts before you run them

    The scripts of this post, from the v1.0 release (immutable: nobody, me included, can change its files or its tag). On the laptop:

    Get-FileHash C:\AW2025Migration\scripts\3*.ps1 -Algorithm SHA256 | Format-Table Hash, Path -AutoSize

    Every hash must match its line below; SHA256SUMS.txt on the release has all of them. If one differs, don’t run it.

    FileSHA-256
    aw2025-azure-migration-v1.0.zip0db411127783f4f2c604211d8293b2854a7776b0289d54b57344890e73c45d4f
    30_Backup-Source.ps101708be0cf96bed86ea90b37a29422c4b29054525d68ec6a59941ce2a5bb09ab
    31_Export-SourceFacts.ps16c5f364b8fdf22df62373212c2c4ddc74670409ba35b51714516f5cede8d7eda
    32_Upload-ToBlob.ps192ee9d6024e6550334c6181858faba0928504cd77a49daa074421d609b3f8842

    Next

    Part 5 is part F, and it all happens on the VM: script 40 installs the TDE certificate from Blob and Key Vault, then restores the newest FULL and every LOG after it, and 41 creates the SQL login with the laptop’s SID and password hash, so the user in the database maps to it with no fix-up. It is also where the one real surprise of the lab was waiting: SQL Server 2025 would not even read the file list of an encrypted backup without the certificate.

    The scripts are on GitHub: calinsqlplay/aw2025-azure-migration (the version these posts use is the v1.0 release).

  • AdventureWorks2025 to an Azure SQL VM, part 3: export what the target needs

    Part 3 of 6. The series: 1. The plan and the lab · 2. Check what is there · 3. Export what the target needs (this post) · 4. Back up and upload · 5. Restore · 6. Check post-migration, and clean up.

    Part 2 ended with a VM that passed all ten gates: it can take the database. This post prepares the two things a backup does not carry on its own.

    • The TDE certificate. An encrypted backup restores only on a server that has the certificate it was encrypted with. If you lose the certificate… just take a wild guess of what happens when you try to restore the DB.
    • The SQL login. The user inside the database comes across with the restore; the login it belongs to lives in master on the laptop and does not.
      I will not go into too much detail here, but without the login you will end up with orphaned users – it can be fixed, but it is extra work.

    AdventureWorks2025 uses neither out of the box. I switched TDE on and created the SQL login on purpose, because a real migration almost always has both (or they should – check Azure SQL and Azure MI, they do come with TDE enabled by default), and both are where migrations go wrong.

    This is the first part that changes the laptop. Both scripts follow the rules from part 1: -WhatIf first, safe to run again, and no password is ever shown, typed or written to a file. Every password goes into Key Vault before anything is protected with it.

    Part C. Export what the target needs

    C1. TDE on the laptop: script 20

    20_Enable-SourceTde.ps1 does six things, in this order, and each one only if it is missing:

    1. A locked key folder, D:\TDE-Keys: Administrators and SYSTEM get full control, the SQL Server service gets modify (it writes the backup of the certificate), nobody else gets in.
      Why a locked key folder? Well, my sad experiences are telling me that there are way too many hands with privileges in older on-prem boxes: the architect because why not, the lead dev because of that pesky folder where we need to do stuff by hand, the sys admin, the DBA, you name it. It is nobody’s fault, it is how things used to run 20 years ago. Locking down the folder reduces the chance that anyone touches sensitive data.
    2. The database master key in master. Its password is generated in memory, stored in Key Vault as aw2025-source-dmk-password, and only then used.
    3. The TDE certificate, AW2025_TDE, in master.
    4. The certificate and its private key, backed up to the key folder (.cer and .pvk), with a new password that goes to Key Vault first, as aw2025-pvk-password. Then the proof: the two files are loaded back as a temporary certificate and its thumbprint compared with the real one. A backup of a certificate that nobody ever opened is a hope, not a backup.
    5. The database encryption key (AES_256, protected by the certificate), then ENCRYPTION ON, and it waits until the database reports encrypted.
    6. FULL recovery, so part D can take log backups. The log chain itself starts with the first FULL backup.

    [laptop, PowerShell as administrator] As a Windows login that is sysadmin in SQL Server, signed in to Azure (B1), with Key Vault Secrets Officer on the vault (01 gave it to you in A3):

    .\20_Enable-SourceTde.ps1 -KeyVault aw2025-kv-1234 -WhatIf
    .\20_Enable-SourceTde.ps1 -KeyVault aw2025-kv-1234

    On AdventureWorks2025 the encryption itself takes seconds. The script waits up to ten minutes; a real database can take hours, while it stays online.

    The key files stay in the locked folder on the laptop, go to Blob storage with the backups in part E, and never into a repository, an e-mail or a ticket. I know it sounds like wishful thinking, but it can be done.

    tempdb gets encrypted too. The moment one database on an instance uses TDE, SQL Server encrypts tempdb as well, for every database on that instance. On a laptop nobody notices; on a busy shared server, measure before and after.

    A source that already uses TDE. The script keeps an existing master key as it is. If the database is already encrypted with a certificate in master, run it with -CertName <that certificate>: it backs that certificate up again with a new password and proves it, and leaves the database alone. It stops, before changing anything, if you name the wrong certificate, and it does not cover TDE with a key in Azure Key Vault (EKM). It also assumes the default instance, MSSQLSERVER.

    Mine ran in under a minute: key folder locked, master key and certificate created, the backup proved, AdventureWorks2025 encrypted, SIMPLE switched to FULL.

    Expected: a CHECK table of six lines, all OK: the master key in master, the certificate with its thumbprint, both key files in the folder, the secret in Key Vault, the database encrypted with that certificate, the database in FULL recovery. Then All OK. AdventureWorks2025 is encrypted with AW2025_TDE (<thumbprint>); key files in D:\TDE-Keys, password in Key Vault as aw2025-pvk-password. Next: 21_Export-SourceLogins.ps1. Write the thumbprint down: part F compares it with the one in the backup.

    C2. The SQL logins, with SID and password hash: script 21

    A database user is tied to its login by the SID, not by the name. Create a login with the same name on the VM and the restored user still will not map to it: different SID, orphaned user, the classic ALTER USER ... WITH LOGIN clean-up afterwards. Create it with the same SID, and the user maps on its own, with no fix-up at all. Add the password hash, and the login keeps its password without anyone knowing it, typing it or resetting it. That is what sp_help_revlogin has done for years; 21_Export-SourceLogins.ps1 does the same in PowerShell.

    For each SQL login that a user of AdventureWorks2025 maps to, it exports: the name, the SID, the password hash, the default database and language, the password policy and expiration flags, whether it is disabled, its server roles and its server-level permissions. All of it goes into one Key Vault secret, aw2025-logins, as JSON. Nothing is written to disk.
    Word of caution here: permissions inside the database (say, EXECUTE on the stored procedures of one schema) come across with the restore; what lives outside it does not. Permissions in msdb or master (SQL Agent roles, proxies, objects in master) and anything granted to a login that is not exported need their own scripts.

    [laptop, PowerShell as administrator] Same login and sign-in as C1:

    .\21_Export-SourceLogins.ps1 -KeyVault aw2025-kv-1234 -WhatIf
    .\21_Export-SourceLogins.ps1 -KeyVault aw2025-kv-1234

    Why Key Vault and not Blob. A password hash is not a password, but it is a secret: it can be attacked offline, at leisure. So it goes where the passwords go, and the VM reads it in part F with its own identity (Key Vault Secrets User). Run the script again later and the secret simply gets a new version.

    Windows logins stay behind. A Windows account of the laptop (or of a domain the VM is not in) cannot exist on the VM, so 21 lists Windows logins but does not export them. 41 reports them again in part F, and you decide what each one comes on the target. Even for machines in the same domain you can have a ton of Windows logins for people who left the company 10 – 15 years ago.

    Mine found one SQL login, AW2025Migration (default database master, policy and expiration off, no server roles or server-level permissions), and no Windows logins mapped to the database.

    Expected: a CHECK table of three lines, all OK: the secret is readable, it holds every SQL login with its SID and hash, and there are no Windows logins to decide on. Then All OK. Next: 30_Backup-Source.ps1.

    Two words on the CHECK tables. Most scripts mark a line that needs a look with CHECK. A few, the ones that build things (00, 01 and 20), say MISSING instead: something that should exist does not. Either way, anything but OK means stop and read the steps above it.

    Check the scripts before you run them

    The scripts of this post, from the v1.0 release (immutable: nobody, me included, can change its files or its tag). On the laptop:

    Get-FileHash C:\AW2025Migration\scripts\2*.ps1 -Algorithm SHA256 | Format-Table Hash, Path -AutoSize

    Every hash must match its line below; SHA256SUMS.txt on the release has all of them. If one differs, don’t run it.

    FileSHA-256
    aw2025-azure-migration-v1.0.zip0db411127783f4f2c604211d8293b2854a7776b0289d54b57344890e73c45d4f
    20_Enable-SourceTde.ps1e00a4966e09289a046984882a152ab3bcc93251b6f4eae85ffc168f02ecf51dd
    21_Export-SourceLogins.ps1589a7edb0cf9d8453bd38c16277940e1deb05b02a155455afc10190ee8201949

    Next

    Part 4 covers parts D and E. Script 30 takes the FULL and LOG backups, checksum-ed and verified, and 31 records the facts of the database right after the last one: row counts, checksums, objects, settings, the hash of the code. Part G holds the VM against those facts. Then 32 uploads the backups, the facts, the key files and the inventory to Blob storage.

    The scripts are on GitHub: calinsqlplay/aw2025-azure-migration (the version these posts use is the v1.0 release).

  • AdventureWorks2025 to an Azure SQL VM, part 2: check what is there

    Part 2 of 6. The series: 1. The plan and the lab · 2. Check what is there (this post) · 3. Export what the target needs · 4. Back up and upload · 5. Restore · 6. Check post-migration, and clean up.

    Part 1 ended with a VM in Azure, a storage account, a Key Vault and the roles that tie them together. Nothing has moved yet, and nothing will in this post either: part B only looks. It records what the laptop has, measures what the drives on both sides can do, and then holds the VM against the laptop in ten go / no-go gates. If a gate fails, you fix it now, while it is cheap, not halfway through a restore.

    Important! As with everything in life, use your judgement and know what to compare, what to change and what to keep. Remember, all cloud providers charge an extravagant amount of money (more so these days) for storage whose performance was good a decade ago. Moving on:

    The facts, the rules and how to read the steps are in Part 0 of part 1. Nothing in part B changes Windows, SQL Server or Azure: the scripts only write their own result files (and 10 uploads its inventory).

    Part B. Check what is there

    B1. The scripts on both machines

    Every later step runs a script from the same folder, C:\AW2025Migration\scripts, on the laptop and on the VM. Get them there once, from the release, and check them before anything runs.

    1. [laptop] Download aw2025-azure-migration-v1.0.zip from the v1.0 release and check its hash against the table at the end of this post. Then unblock it, unpack it and go to the folder:
    Set-Location "$env:USERPROFILE\Downloads"
    Get-FileHash .\aw2025-azure-migration-v1.0.zip -Algorithm SHA256
    Unblock-File .\aw2025-azure-migration-v1.0.zip
    New-Item -ItemType Directory -Force C:\AW2025Migration\scripts | Out-Null
    Expand-Archive .\aw2025-azure-migration-v1.0.zip C:\AW2025Migration\scripts -Force
    Set-Location C:\AW2025Migration\scripts
    1. [VM] Copy the same zip to the VM’s Downloads folder (copy in Explorer on the laptop, paste in Explorer in the Remote Desktop window), then run the same six lines there.
    2. [laptop] The laptop scripts talk to Azure through the Az modules. Windows PowerShell 5.1 needs TLS 1.2 and the NuGet provider before Install-Module works:
    [Net.ServicePointManager]::SecurityProtocol = 'Tls12'
    Install-PackageProvider NuGet -MinimumVersion 2.8.5.201 -Force
    Install-Module Az.Accounts, Az.Storage, Az.KeyVault -Scope CurrentUser
    1. [laptop] Sign in to the lab subscription, by its tenant ID (Microsoft Entra ID > Overview in the portal), and check where you landed:
    Connect-AzAccount -TenantId <your lab tenant ID>
    Get-AzContext

    The VM needs none of this: no Az module, no sign-in. Its managed identity does the talking (part 1, A3).

    Two machines, two accounts. If the laptop already knows another Microsoft account (work, a client), a plain Connect-AzAccount can sign you in to that one instead. With -TenantId it cannot (I learned this the not-so-fun way). Get-AzContext tells you which subscription you are in: check it before every laptop script that talks to Azure.

    Scripts that will not run. Windows marks every file that came from the internet, and PowerShell refuses a marked script (“is not digitally signed”). Unblocking the zip before unpacking it (step 1) avoids that. If the execution policy itself blocks scripts on the machine, allow them for this window only: Set-ExecutionPolicy -Scope Process Bypass.

    Expected: on both machines, C:\AW2025Migration\scripts holds the 14 scripts, README.md and LICENSE; the zip’s hash matches the table. On the laptop, Get-AzContext shows the lab subscription and your lab account.

    B2. Inventory of the laptop: script 10

    The VM has to match the laptop where it matters, and you cannot match what you never wrote down. 10_Get-SourceInventory.ps1 writes it all down, once, before anything on the laptop changes:

    • the machine: Windows version, CPU cores, memory, time zone, every drive (size, free space, file system, allocation unit);
    • the instance: version and CU, edition, collation, authentication mode, the CPUs SQL Server may use, memory and other settings, services and their accounts, default paths, tempdb, full-text and FILESTREAM, logins by type, linked servers, server triggers, credentials, availability groups, jobs;
    • the database: size, files and their drives, recovery model, compatibility level, owner, collation, TDE, and everything that ties it to a target: Enterprise-only features, FILESTREAM, memory-optimized data, full-text, CDC, replication, CLR assemblies, Service Broker, users and the logins they map to, jobs that name it.

    The result is a JSON file in D:\Backups\<laptop>\INVENTORY\, uploaded to inventory/<laptop>/ in the container, where script 12 on the VM picks it up in B4. It holds no passwords, keys or hashes.

    [laptop, PowerShell as administrator] As a Windows login that is sysadmin in SQL Server, signed in to Azure (B1):

    .\10_Get-SourceInventory.ps1 -StorageAccount aw2025mig12345 -WhatIf
    .\10_Get-SourceInventory.ps1 -StorageAccount aw2025mig12345

    Again, this is on my laptop, where I have 3 separate drives: OS, DBData and DBLog. DBData is the data drive, where I also have the backups folder. If your drives are laid out differently, add -BackupRoot with a folder that has room for the backups in part D, and use the same value there.

    What mine said about AdventureWorks2025: 328 MB of data (296 MB used), a 200 MB log, SIMPLE recovery, compatibility level 170, owned by my Windows login, no TDE yet, no Enterprise-only features, no FILESTREAM, three full-text indexes, Query Store on, one user mapped to the SQL login AW2025Migration, and no jobs that name it. Two of those come back as gates in B4: the full-text indexes (G8) and the SQL login (G7).

    Note on a storage account that is not there. If you ran 00 and then 01 again with the same storage account name, the laptop may still talk to the old, deleted account for a while: 10 stops with “Container backups not reachable”. The laptop’s DNS cache remembers the old address. Run ipconfig /flushdns, wait a few minutes, and run 10 again.

    Expected: a CHECK table of four lines, all OK: the inventory file written, the same file in Blob, SQL Server using every CPU of the machine, and no FILESTREAM. Then All OK. Next: 11_Test-DiskSpd.ps1 on this machine (optional), then 12_Test-TargetReadiness.ps1 on the Azure VM.

    B3. DiskSpd on both machines: script 11 (optional)

    The inventory says how big the drives are; it says nothing about how fast they are. 11_Test-DiskSpd.ps1 runs Microsoft DiskSpd in the I/O patterns SQL Server uses, the same seven tests on each machine, so the two can be put side by side:

    TestPatternStands for
    018K random readdata file reads
    028K random writecheckpoint
    038K random, 70% read / 30% writea mixed OLTP load
    0464K sequential readscans, read-ahead
    0564K sequential writebulk load
    061M sequential readbackup and restore
    074K write, 1 thread, 1 I/O at a timethe transaction log flush

    Every test bypasses the Windows cache and writes through, as SQL Server does, and records latency as well as throughput.

    Read this before you run it. It drives the disk flat out for about ten minutes. A drive that holds user database files is refused unless you add -Force: on a lab laptop that is fine, on a production server only in an agreed window, and better not at all. It also measures what a drive can do, not what the database needs: a laptop NVMe drive gives hundreds of thousands of I/Os per second, an Azure VM gives what its disks and its VM size allow. Size Azure on what the workload uses; use this test to see the difference in latency and to prove the VM’s disks deliver what you pay for.

    1. [laptop, PowerShell as administrator] The data drive. -Download fetches DiskSpd from Microsoft’s GitHub the first time; -Force because D: holds the database files:
    .\11_Test-DiskSpd.ps1 -TargetDir D:\DiskSpdTest -Download -Force -WhatIf
    .\11_Test-DiskSpd.ps1 -TargetDir D:\DiskSpdTest -Download -Force

    The results land next to the script, in a folder named DiskSpd <computer> <drive> <date_time>: one .txt per test, 00 environment.txt and summary.csv.

    1. [VM] Copy that whole folder to the VM (Remote Desktop clipboard, as in B1), then test the VM’s data drive and compare:
    .\11_Test-DiskSpd.ps1 -TargetDir F:\DiskSpdTest -Download -CompareWith "C:\AW2025Migration\scripts\<laptop folder>\summary.csv"

    Repeat for the log drives (E: on the laptop, G: on the VM) if the log flush matters to you: test 07 is the one to look at.

    For the record, my laptop’s data drive (a Samsung 990 Pro): 412,000 IOPS of 8K random reads at a p99 latency of 0.40 ms, 3,300 MiB/s of sequential reads and writes, and a log flush (test 07) of 0.03 ms on average. No Azure managed disk comes near that, and it does not need to: AdventureWorks2025 uses a tiny part of it. On the VM I ran a short smoke test only, to prove the script and the comparison work.

    Note here: second-hand laptop with SSDs purchased when SSDs were affordable. Perhaps we will look back at this RAM-pocalypse and SSD-pocalypse in the future and laugh, but right now we can only dream of those prices. As of 2024 – early 2025, a VM with 2 GB/s throughput was your middle-of-the-road choice. These days is pushing again the higher end of pricing. I will close by pointing out that no, I am not using IOPS.

    Expected: on each machine a CHECK table of three lines, all OK: every test ran without a DiskSpd error, every test gave IOPS and latency, the test file was deleted. Then All OK. Summary: <path>\summary.csv. With -CompareWith, a table of both machines, test by test.

    B4. Readiness gates on the VM: script 12

    Now the VM is held against the laptop. 12_Test-TargetReadiness.ps1 reads the laptop’s inventory from Blob (B2), looks at the VM and runs ten go / no-go gates. A gate that says CHECK is either fixed now or decided and written down, before a single backup is restored.

    GateChecksWhy it matters
    G1server collation as the laptop’stempdb and the system databases use it; temporary tables follow it
    G2SQL Server version the same or newera backup never restores to an older version
    G3the edition takes the databasean Enterprise-only feature in use needs Enterprise (or Enterprise Developer)
    G4@@SERVERNAME is the machine namejobs, linked servers and some tools rely on it
    G5time zone as the laptop’sbackup file names and job schedules are in local time (A2)
    G6free spacethe data and log drives take the database, the staging drive takes the backups
    G7SQL Server authentication, if SQL logins are useda SQL login cannot sign in to a Windows-only server
    G8full-text and FILESTREAM, where the laptop uses themthe restore needs the same features installed
    G9SQL Server uses every CPU of the VMan edition or VM layout can hold it to fewer
    G10the VM’s identity reaches Blob and Key Vaultparts F and G depend on it (the roles from A3)

    It also shows, without gating on them: VM size and region, the licence (free Developer or paid), memory settings, tempdb and the services.

    [VM, PowerShell as administrator] As a Windows login that is sysadmin in SQL Server. No Az module and no sign-in: the VM’s managed identity reads Blob and Key Vault. -SourceServer is your laptop’s name (mine is the default):

    .\12_Test-TargetReadiness.ps1 -StorageAccount aw2025mig12345 -KeyVault aw2025-kv-1234 -SourceServer <your laptop's name>

    It changes nothing, so there is no -WhatIf.

    Mine came back with nine gates OK and one CHECK: G7. The laptop’s database has a user mapped to a SQL login, and the Azure image installs SQL Server with Windows authentication only (configuring SQL Server post-install is another series in itself, but we will not cover it here). Script 41 in part F can switch SQL Server authentication on (-EnableSqlAuth), but for a one-off it is quicker by hand, and it is better fixed now than discovered at the end:

    1. [VM, SSMS] Right-click the server > Properties > Security > SQL Server and Windows Authentication mode > OK.
    2. [VM, PowerShell] Restart SQL Server, and Agent with it:
    Restart-Service MSSQLSERVER -Force
    Start-Service SQLSERVERAGENT
    1. Run 12 again.

    max server memory. On the image it is not set, so SQL Server may take all of the VM’s 16 GB. 12 warns about it but does not gate on it. Set it before a real workload arrives: on a small VM, physical memory minus 4 GB is a fair start.

    Important: as of 2026, Microsoft recommends 75% of the available system memory not used by other processes (https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/server-memory-server-configuration-options?view=sql-server-ver17). Of course, you are also expected to know the limitations of SQL Server Editions (read Enterprise and Standard, the most used ones).
    Where am I going with this? Standard Edition supports 128 GB of RAM for the buffer pool in SQL Server 2022 and 256 GB in SQL Server 2025. Use your common sense here.
    Alright, moving on:

    Expected: all ten gates OK, then Ready. <VM> can take AdventureWorks2025 from <laptop>. Next: 20_Enable-SourceTde.ps1 on the source. If you picked the paid image in A2, a yellow licence line says so here too.

    Check the scripts before you run them

    The scripts of this post, from the v1.0 release (immutable: nobody, me included, can change its files or its tag). On each machine, after B1:

    Get-FileHash C:\AW2025Migration\scripts\1*.ps1 -Algorithm SHA256 | Format-Table Hash, Path -AutoSize

    Every hash must match its line below; SHA256SUMS.txt on the release has all of them. If one differs, don’t run it.

    FileSHA-256
    aw2025-azure-migration-v1.0.zip0db411127783f4f2c604211d8293b2854a7776b0289d54b57344890e73c45d4f
    10_Get-SourceInventory.ps16f0367eb3b5996181a99476b9f36950e295d41b5419b3a8c331ced5c6f66d80f
    11_Test-DiskSpd.ps1b3ff522514242b4ec524ee5dc67ca3b77ebc5cab67cce17294dd921226f6ac42
    12_Test-TargetReadiness.ps16f0765525138cd5f27d3bfc30b215238eee6f7ac9fdf68fef09322faa9f2b930

    Next

    Part 3 is part C, and the first one that changes something on the laptop: script 20 switches on TDE, exports the certificate and proves the export opens, with every password going straight into Key Vault; script 21 exports the SQL login with its SID and password hash, so the user in the database still maps to it on the VM.

    The scripts are on GitHub: calinsqlplay/aw2025-azure-migration (the version these posts use is the v1.0 release).

  • AdventureWorks2025 to an Azure SQL VM, part 1: the plan and the lab

    Part 1 of 6. The series: 1. The plan and the lab (this post) · 2. Check what is there · 3. Export what the target needs · 4. Back up and upload · 5. Restore · 6. Check post-migration, and clean up.

    A week ago I wrote about site-to-site migration and rollback: the method, in one long T-SQL script (apologies for that). This series does the whole thing end to end, using AdventureWorks2025, which goes from my laptop (SQL Server 2025 Enterprise Developer) to SQL Server on an Azure VM, with TDE on and a SQL login that has to keep working on the other side.

    Everything is scripted in PowerShell, every script is on GitHub (link in each post), and the gotchas, caveats, notes worth knowing about are in the posts.

    The method comes from a migration toolkit I put together for a SQL Server move to cloud (again, provider not important here). Azure has other names for the same pieces: a managed identity instead of an instance role, Key Vault instead of Secrets Manager, Blob storage instead of S3 – see? I gave away the other cloud provider name. The order of the work does not change.

    The plan

    The whole migration is one runbook in seven parts, A to G, spread over six posts. The numbers are the scripts; the first digit tells you the part: 0 is A, 1 is B, and so on.
    One note of caution here – full disclosure and transparency, the real migration I did have a ton of other checks and scripts. What you will see here has been generated and adapted using Claude, who happens to be far more adept at this than I will ever be.
    Having said that, make sure you run these in your own test environment (more on that later). You can freely adapt and use any of them in your work but if something goes wrong, don’t come knocking on my door because I did not do your due diligence.

    PartScriptsRuns onPost
    A. Prepare Azure01 (and 00 to take it down again)portal, Cloud Shell1 (this one)
    B. Check what is there10 inventory, 11 DiskSpd, 12 readiness gateslaptop, then VM2
    C. Export what the target needs20 TDE certificate, 21 loginslaptop3
    D. Back up30 backups, 31 cutover snapshotlaptop4
    E. Upload32laptop4
    F. Restore40 restore, 41 loginsVM5
    G. Check post-migration50, and 99 to reset the labVM6

    Part 0. The facts

    Before anything runs, write down what you are moving and where it goes. The tables show my lab; fill in your own values as you go. Storage account and vault names must be unique across Azure, so yours will differ from the examples.

    0.1 The two servers

    Source: the laptopTarget: the Azure VM
    NamePRECISION7760AW2025Migration (VM name and Windows name)
    SQL ServerSQL Server 2025 Enterprise Developer, RTM (17.0.1000.7)SQL Server 2025 Enterprise Developer from the Azure image, CU10 (17.0.5045.3): same major version, newer CU
    CollationSQL_Latin1_General_CP1_CI_ASthe same (the image’s default)
    CPU / memoryrecord yours2 vCPUs, 16 GB (Standard E2ads v7)
    DrivesC: Windows; D: data; E: log and tempdbC: Windows; D: temporary disk, tempdb; F: data; G: log
    Time zoneGTB Standard TimeUTC from the image, set to the laptop’s in A2
    RegionEast US (see the region box in A2)

    0.2 Azure

    PieceWhat it is forName in my lab
    Subscriptiona new free account, used for this and nothing else
    Resource groupholds everything below, so one delete removes it allAW2025Migration
    VMthe target SQL ServerAW2025Migration
    Storage account, private container backupsthe meeting point: the laptop uploads, the VM downloadsaw2025mig12345
    Key Vault (RBAC permissions)the passwords and the exported loginsaw2025-kv-1234
    The VM’s managed identitylets the VM reach storage and Key Vault with no password or key on itsystem-assigned, switched on by 01

    What goes in the container, and who uses it:

    Blob pathWhatWritten byRead by
    inventory/<laptop>/the inventory of the laptop1012
    keys/<laptop>/the TDE certificate and its private key (.cer, .pvk)3240
    <laptop>/AdventureWorks2025/FULL/ and /LOG/the backups3240
    facts/<laptop>/AdventureWorks2025/the cutover snapshot3250

    Who may do what (01 grants it):

    WhoRoleOnSo it can
    the VMStorage Blob Data Contributorthe storage accountread and write the blobs
    the VMKey Vault Secrets Userthe vaultread secrets, never write them
    youKey Vault Secrets Officerthe vaultcreate and read secrets

    The laptop is not in Azure, so it has no identity: the laptop scripts use your own sign-in (Connect-AzAccount).

    0.3 Secrets in Key Vault (names only)

    SecretHoldsCreated byRead by
    aw2025-source-dmk-passwordthe password of the database master key in master on the laptop20nobody else: it stays with the laptop
    aw2025-pvk-passwordthe password of the TDE private key file (.pvk)2040, on the VM
    aw2025-loginsthe SQL logins: names, SIDs, password hashes2141
    aw2025-login-<name>-passwordoptional: a login’s password, for the sign-in test in 41you, by hand41

    The TDE certificate is AW2025_TDE. The VM’s own master key password is generated by 40, used once and never stored: the certificate files and their password are all a rebuilt VM needs.

    0.4 The database

    The source is my laptop: SQL Server 2025 Enterprise Developer, AdventureWorks2025 (328 MB of data, 200 MB of log – most of it empty, but still), and one SQL login, AW2025Migration, mapped to a user in the database (db_ddladmin, db_datareader, db_datawriter). Out of the box the database is in SIMPLE recovery and not encrypted: 20 switches on TDE and FULL recovery, so the migration has a certificate and a log chain to carry.

    0.5 Where the scripts are

    WhereWhat
    GitHub, release v1.0all the scripts, with the run order in the README; check them first (see the end of this post)
    Cloud Shell, your home folder00 and 01 (Manage files > Upload)
    laptop: C:\AW2025Migration\scripts10, 11, 20, 21, 30, 31, 32, 99
    VM: C:\AW2025Migration\scripts11, 12, 40, 41, 50, 99
    laptop: D:\Backups\<laptop>\ and D:\TDE-Keyswhat the laptop scripts write: inventory, backups, facts; the key files (locked to Administrators and SYSTEM)

    0.6 Rules for the whole job

    Every script plays by the same rules, because I did not want to babysit any of them:

    • PowerShell only: Windows PowerShell 5.1 on the laptop and the VM, PowerShell in Cloud Shell. No Bash, no paste-this-block – I tried, was not really smooth sailing for me.
    • Prerequisites first: modules, sign-in, rights, the right machine. It stops before it changes anything.
    • -WhatIf first, always. It shows what it would do. If something goes wrong, this is the first line of defense – it’s not like you want to throw some weird output directly to prod, right? RIGHT???
    • Safe to run again: it looks before it acts and creates only what is missing.
    • It stops at the first error and names the step.
    • It ends with a CHECK table: one line per thing that must be true, OK or MISSING.
    • No password is ever shown or typed. The script generates it, stores it in Key Vault first, then uses it.

    0.7 How to read the steps

    Each step says where it runs: [browser], [portal], [Cloud Shell], [laptop] or [VM]; and with what: PowerShell (elevated on the laptop and the VM, unless the step says otherwise) or SSMS. Expected says what a correct result looks like. Write your own values down as you go (names, counts, sizes): later steps compare against them.

    Part A. Prepare Azure

    A1. The account

    [browser] The target lives in a brand-new Azure free account, on an Outlook.com address made for this and nothing else. The free account gives $200 of credit for 30 days, so prepare the scripts before you sign up, not after.

    1. Create the Outlook.com address, then the Azure free account with it.
    2. Set up MFA on the new account before anything else (next box).

    Important: MFA is not optional any more. The portal and every Azure PowerShell sign-in ask for it. Set up the Authenticator app or a passkey on the new account before anything else. Managed identities, which do most of the work later, are not affected.

    Expected: you sign in to the portal with MFA, and the new subscription shows under Subscriptions.

    A2. The VM

    [portal] Put the VM in a new resource group, AW2025Migration, and give the VM the same name: 01 and the later scripts expect those names unless you pass others.

    Note: you might encounter “not accepting new customers”. My first VM went to West Europe, and every resource of the deployment was refused (RequestDisallowedByAzure). New subscriptions are not welcome in every region. I ended up in East US; North Europe or Sweden Central are worth a try first if you are in Europe.

    The VM itself, from the portal: a SQL Server 2025 image on Windows Server 2025, two vCPUs and 16 GB (Standard E2ads v7). Three things to get right in the wizard:

    1. The image. You want Free SQL Server License: SQL Server 2025 Enterprise Developer on Windows Server 2025. I got the paid Enterprise one, billed per hour, and found out from SELECT SERVERPROPERTY('Edition'): Enterprise Edition: Core-based Licensing. Run that query first thing on any new VM. The credit covered my lab; it would not cover a mistake on a real subscription.
      For someone who makes a living working with cloud providers, you would expect to know how to choose a VM. Apparently not.
    2. The disks. The SQL image gives you a 1 TB data disk and a 1 TB log disk by default, billed even while the VM is stopped, and a managed disk never shrinks. Set small ones on the SQL Server settings tab.
    3. The time zone. The VM comes up in UTC. My backup file names carry the laptop’s local time and the restore reads them, so I set the VM to the laptop’s zone: Set-TimeZone -Id 'GTB Standard Time', then restart SQL Server. Of course, your time zone might be different, so there is that.

    Once it is up:

    1. [VM] Connect with Remote Desktop (Connect > RDP in the portal).
    2. [VM, SSMS] Check the edition: SELECT SERVERPROPERTY('Edition');
    3. [VM, PowerShell] Time zone, then restart SQL Server and start Agent (Manual on the image):
    Set-TimeZone -Id 'GTB Standard Time'
    Restart-Service MSSQLSERVER -Force
    Start-Service SQLSERVERAGENT

    Expected: the VM is running in AW2025Migration; the edition is a Developer edition, not Enterprise Edition: Core-based Licensing; the data and log disks have the size you chose; Get-TimeZone shows the laptop’s zone.

    A3. The Azure base: script 01

    [Cloud Shell, PowerShell] With the VM running, 01_New-AzureLabBase.ps1 builds everything else the migration needs:

    • a storage account (TLS 1.2, no public blob access) with a private container, backups, for the backups and the TDE key files;
    • a Key Vault with RBAC permissions, for the passwords and the logins (you did not really think you get to copy paste passwords, did you?);
    • the VM’s system-assigned managed identity, switched on;
    • who may do what: the VM gets Storage Blob Data Contributor on the storage account and Key Vault Secrets User on the vault; I get Key Vault Secrets Officer on the vault.

    Before any of that, it registers the resource providers a new subscription does not have yet (storage, Key Vault and three more): without them, the first Key Vault fails with MissingSubscriptionRegistration. Every step looks first and creates only what is missing.

    The managed identity is the part worth understanding. The VM asks Azure’s metadata endpoint for a token and uses it against Blob storage and Key Vault. No key, password or certificate for Azure ever sits on the VM, and the restore scripts in part F need no Az module at all. The laptop is not in Azure, so it uses my sign-in instead.
    That reminds me: it is very useful to install the Azure PS module.

    1. Open Cloud Shell from the portal, in PowerShell mode (not Bash).
    2. Upload 01_New-AzureLabBase.ps1 and 00_Remove-AzureLabBase.ps1 (Manage files > Upload) and check them against the table at the end of this post: Get-FileHash ./01_New-AzureLabBase.ps1.
    3. Run 01 with -WhatIf first, then for real, with your own names (both must be unique across Azure):
    ./01_New-AzureLabBase.ps1 -StorageAccount aw2025mig12345 -KeyVault aw2025-kv-1234 -WhatIf
    ./01_New-AzureLabBase.ps1 -StorageAccount aw2025mig12345 -KeyVault aw2025-kv-1234

    The eagle-eyed among you will notice that the above script is the same except for the -WhatIf part. Ideally, you will run the first script, check what is what, then run it without -WhatIf.

    01 assumes the resource group (for me, yours might be different) and the VM are both called AW2025Migration, in East US. If yours are not, add -ResourceGroup, -VmName and -Location (the VM’s region, for example northeurope) to both lines.

    Expected: it ends with a CHECK table: resource group, storage account, private container, vault with RBAC, the VM’s identity, and one line per role. All of them should say OK, then:

    All OK. Storage account: aw2025mig12345 Key Vault: aw2025-kv-1234 Container: backups

    Kind of important: roles take a moment. A role assignment can take a minute or two to apply, so script 01 retries. If a later script says you cannot read the vault’s secrets, wait a few minutes before you look for anything else.

    00_Remove-AzureLabBase.ps1 takes all of this down again, and purges the vault so its name can be used again. More on that, and on a purge that is slower than it says, in part G.

    Next

    Part 2 is part B, and it looks before it touches anything: an inventory of the laptop, DiskSpd on both machines, and ten go / no-go gates on the VM. One of them failed, and I fixed it by hand.

    The scripts are on GitHub: calinsqlplay/aw2025-azure-migration (the version these posts use is the v1.0 release). As in my last post, Claude wrote much of the scripts with me, and its comments are more thorough than mine would have been. The runs and the decisions are mine.

    Check the scripts before you run them

    Download aw2025-azure-migration-v1.0.zip from the v1.0 release. That release is immutable: nobody, me included, can change its files or its tag. Before you unzip it:

    Set-Location "$env:USERPROFILE\Downloads"
    Get-FileHash .\aw2025-azure-migration-v1.0.zip -Algorithm SHA256

    The hash must match the zip’s line below. Each post lists the scripts it uses, and SHA256SUMS.txt on the release has all of them. If one differs, don’t run it.

    FileSHA-256
    aw2025-azure-migration-v1.0.zip0db411127783f4f2c604211d8293b2854a7776b0289d54b57344890e73c45d4f
    01_New-AzureLabBase.ps13074b20bca2eea4612755a031b98c88230bc3ff48253f2b17e002cde881209cd
    00_Remove-AzureLabBase.ps161fe8c80e1836b8f5a43ff1af6e71c9a891e79e73881bf0fa0427a1aa914e644
  • Site-to-site migration and rollback

    First things first: Hugo, one of the best humans to have walked the face of the Earth passed away. You can read about his last moments here: https://sqlserverfast.com/blog/hugo/2026/11/final-post/. I, for once, am lost for words.
    Go grab his video trainings (basically for free for the depth of knowledge you will get), that is the least we can all do for the family: https://sqlserverfast.com/the-sqlserverfast-execution-plan-video-training/.

    Back to the topic, rushed, as usual, apologies again and again: I am involved in a migration where we need to lift every single bit that a company owns to the cloud. That exercise includes the databases as well (SQL Server 202x to a similarly spec-ed VM in the cloud, vendor not important).

    I took the scripts I gathered throughout the past 10 years, the scripts I am using for the migration to the cloud VM, the scripts used for rollback (from cloud VM to on-prem VM) and gave them to Claude. Extremely chatty fellow, over documented things (you will se things like script 45, script 90 or similar, do not have the time to remove all of these, sorry)
    The idea is simple: what scripts to I need for the rollback? Imagine the following scenario:

    Local: LOC_FULL ── LOC_LOG_1 ── LOC_LOG_2 ── LOC_LOG_TAIL (Local frozen here)
    │
    Remote: REM_FULL_1 ── REM_LOG_1 ── REM_DIFF_1 ── REM_LOG_2 ── REM_FULL_2 ── REM_DIFF_2 ── REM_LOG_3 ── REM_LOG_TAIL

    Assuming the above sequence, if I need to roll back to on-prem, do I need to go restore from ALL the backups from the remote site or is it enough to restore only the REM_LOG_x backups and I can safely leave out REM_FULL_x and REM_DIFF_x?
    Spoiler alert, only the log backups should suffice – in non-technical terms, REM_LOG_1 transaction log backup will pick up from where LOC_LOG_TAIL transaction log backup stopped. This is hugely important if you have multi-TB databases.

    Script explanation:
    Part 0 : setup
    Part 1 – 5: migrate from on-prem to cloud, work in cloud, rollback and check all good
    Part 6 – 10: test full and diff backups (to a different database, you will see in the script itself).

    Because the chatty Claude already documented the script far better than I would ever be able to, I will just leave it here.

    /* Cutover and rollback, simulated on one local instance with AdventureWorks.
    Local test only.
    Two copies of AdventureWorks play the two servers:
    Local_AW = the local (on-premises) server Remote_AW = the remote server in cloud
    What it shows: after the cutover, Local needs ONLY Remote's log backups to come back up to date.
    Remote's FULL and DIFF backups of the weekend are taken but never used for the normal rollback.
    Sections 6-10 then test the DIFFs: what happens if one is tried on the frozen copy, and the fallback
    when the frozen copy is lost (rebuild from Remote's FULL + DIFF + logs).
    Sequence:
    1. Local, normal days: FULL, rows, LOG, rows, LOG
    2. Friday cutover: row, tail-log WITH NORECOVERY on Local (script 90) -> Local_AW RESTORING (frozen)
    Remote_AW built from Local's FULL + LOGs + tail-log, recovered (45 + 91)
    3. Weekend on Remote: rows, FULL_1 (step 8), LOG_1, DIFF_1, rows, LOG_2, FULL_2 (the 05:00 one), rows, DIFF_2, LOG_3, rows
    4. Monday rollback: tail-log WITH NORECOVERY on Remote (script 93) -> Remote_AW RESTORING
    on Local_AW: Remote's LOGs + Remote's tail-log only, then RECOVERY (script 95)
    5. Check: Local_AW has every row written on Local and on Remote
    6. What SQL Server recorded for Remote's backups: which FULL each DIFF is based on
    7. Test A: a DIFF tried on the frozen copy expected Msg 3136; the copy stays RESTORING and the logs still apply
    8. Test B: FULL_2 + DIFF_1 (the wrong pair) expected Msg 3136: DIFF_1's base is FULL_1
    9. Test C: FULL_2 + DIFF_2 + LOG_3 + tail-log expected to WORK: the fallback with the latest FULL and DIFF
    10. Test D: FULL_1 + DIFF_1 + LOG_1..3 + tail-log expected to WORK: Msg 4326 for LOG_1 (too early), FULL_2 does not break the chain
    Tests A-D restore into a third database, Rebuild_AW, so Local_AW and Remote_AW are left as section 5 left them.
    Tests A and B fail on purpose: read the Messages tab, the red lines there are the expected ones.
    Run the whole script (F5). The source database (@src) is only backed up (COPY_ONLY), not changed.
    Files go to <instance default backup folder>\AW_rollback_sim\ (SQL Server 2019 or later for that property). */
    /* ---------- 0. Setup: Local_AW as a copy of AdventureWorks ---------- */
    -- File names. The MOVE clause of every restore is built from the backup file itself (its file list in msdb),
    -- so it uses whatever logical names that backup carries, not the source database's.
    -- Local_AW's logical files are renamed at setup to AW_sim_data_<file_id> / AW_sim_log_<file_id>: nothing keeps
    -- the source's names. Remote_AW and Rebuild_AW keep the logical names of the backup they come from (as BIAS
    -- on EC2 keeps the names it had on Wyton); their physical files are named <database>_<file_id>.mdf / .ldf.
    USE master;
    IF OBJECT_ID(N'tempdb..#move_for') IS NOT NULL
    DROP PROCEDURE #move_for;
    GO
    CREATE PROCEDURE #move_for
    @backup NVARCHAR(400),
    @target sysname,
    @move NVARCHAR(MAX) OUTPUT
    AS
    BEGIN
    SET NOCOUNT ON;
    DECLARE @data NVARCHAR(400) = CAST(SERVERPROPERTY('InstanceDefaultDataPath') AS NVARCHAR(400)),
    @log NVARCHAR(400) = CAST(SERVERPROPERTY('InstanceDefaultLogPath') AS NVARCHAR(400)),
    @set INT;
    SELECT TOP (1)
    @set = s.backup_set_id
    FROM msdb.dbo.backupset AS s
    JOIN msdb.dbo.backupmediafamily AS m
    ON m.media_set_id = s.media_set_id
    WHERE m.physical_device_name = @backup
    ORDER BY s.backup_set_id DESC;
    IF @set IS NULL
    THROW 50000, N'#move_for: no backup history in msdb for that file.', 1;
    SELECT @move
    = STRING_AGG(
    CAST(N'MOVE N''' + REPLACE(f.logical_name, N'''', N'''''') + N''' TO N'''
    + CASE
    WHEN f.file_type = 'L' THEN
    @log
    ELSE
    @data
    END + @target + N'_' + CAST(f.file_number AS NVARCHAR(10))
    + CASE
    WHEN f.file_type = 'L' THEN
    N'.ldf'
    ELSE
    N'.mdf'
    END + N'''' AS NVARCHAR(MAX)),
    N', '
    )
    FROM msdb.dbo.backupfile AS f
    WHERE f.backup_set_id = @set
    AND f.file_type IN ( 'D', 'L' );
    END;
    GO
    SET NOCOUNT ON;
    DECLARE @src sysname = N'AdventureWorks'; -- change if your copy has another name
    IF DB_ID(@src) IS NULL
    THROW 50000, N'Set @src to the name of your AdventureWorks database.', 1;
    IF DB_ID(N'Local_AW') IS NOT NULL
    OR DB_ID(N'Remote_AW') IS NOT NULL
    OR DB_ID(N'Rebuild_AW') IS NOT NULL
    THROW 50000, N'Local_AW, Remote_AW or Rebuild_AW already exists: run the clean-up at the end first.', 1;
    DECLARE @dir NVARCHAR(400) = CAST(SERVERPROPERTY('InstanceDefaultBackupPath') AS NVARCHAR(400));
    IF RIGHT(@dir, 1) <> N'\'
    SET @dir += N'\';
    SET @dir += N'AW_rollback_sim\';
    EXEC master.sys.xp_create_subdir @dir;
    IF OBJECT_ID(N'tempdb..#sim') IS NOT NULL
    DROP TABLE #sim;
    CREATE TABLE #sim
    (
    k VARCHAR(20) PRIMARY KEY,
    v NVARCHAR(MAX)
    );
    INSERT #sim
    VALUES
    ('dir', @dir);
    DECLARE @sql NVARCHAR(MAX),
    @move NVARCHAR(MAX);
    SET @sql
    = N'BACKUP DATABASE ' + QUOTENAME(@src) + N' TO DISK = N''' + @dir
    + N'seed.bak'' WITH COPY_ONLY, INIT, FORMAT, CHECKSUM;';
    EXEC (@sql);
    DECLARE @seed NVARCHAR(400) = @dir + N'seed.bak';
    EXEC #move_for @backup = @seed,
    @target = N'Local_AW',
    @move = @move OUTPUT;
    SET @sql = N'RESTORE DATABASE Local_AW FROM DISK = N''' + @seed + N''' WITH RECOVERY, ' + @move + N';';
    EXEC (@sql);
    -- rename Local_AW's logical files, so no copy carries the source's names
    SELECT @sql
    = STRING_AGG(
    CAST(N'ALTER DATABASE Local_AW MODIFY FILE (NAME = N''' + REPLACE(name, N'''', N'''''')
    + N''', NEWNAME = N''AW_sim_' + CASE
    WHEN type = 1 THEN
    N'log_'
    ELSE
    N'data_'
    END + CAST(file_id AS NVARCHAR(10)) + N''');' AS NVARCHAR(MAX)),
    N' '
    )
    FROM sys.master_files
    WHERE database_id = DB_ID(N'Local_AW')
    AND type IN ( 0, 1 );
    EXEC (@sql);
    ALTER DATABASE Local_AW SET RECOVERY FULL;
    EXEC (N'USE Local_AW; CREATE TABLE dbo.Movement (id int IDENTITY(1,1) PRIMARY KEY, note varchar(80) NOT NULL, written_on varchar(10) NOT NULL, at datetime2(3) NOT NULL DEFAULT SYSDATETIME());');
    GO
    /* ---------- 1. Local, normal days: FULL, rows, LOG, rows, LOG ---------- */
    DECLARE @dir NVARCHAR(400) =
    (
    SELECT v FROM #sim WHERE k = 'dir'
    ),
    @sql NVARCHAR(MAX);
    SET @sql = N'BACKUP DATABASE Local_AW TO DISK = N''' + @dir + N'LOC_FULL.bak'' WITH INIT, FORMAT, CHECKSUM;';
    EXEC (@sql);
    INSERT Local_AW.dbo.Movement
    (
    note,
    written_on
    )
    VALUES
    ('Local: normal day 1', 'Local'),
    ('Local: normal day 2', 'Local');
    SET @sql = N'BACKUP LOG Local_AW TO DISK = N''' + @dir + N'LOC_LOG_1.trn'' WITH INIT, FORMAT, CHECKSUM;';
    EXEC (@sql);
    INSERT Local_AW.dbo.Movement
    (
    note,
    written_on
    )
    VALUES
    ('Local: normal day 3', 'Local');
    SET @sql = N'BACKUP LOG Local_AW TO DISK = N''' + @dir + N'LOC_LOG_2.trn'' WITH INIT, FORMAT, CHECKSUM;';
    EXEC (@sql);
    GO
    /* ---------- 2. Friday cutover: freeze Local, build Remote from Local's backups ---------- */
    DECLARE @dir NVARCHAR(400) =
    (
    SELECT v FROM #sim WHERE k = 'dir'
    ),
    @sql NVARCHAR(MAX);
    INSERT Local_AW.dbo.Movement
    (
    note,
    written_on
    )
    VALUES
    ('Local: last transaction before the tail-log', 'Local');
    -- script 90: tail-log WITH NORECOVERY -> Local_AW stays RESTORING, frozen
    SET @sql
    = N'ALTER DATABASE Local_AW SET SINGLE_USER WITH ROLLBACK IMMEDIATE; ' + N'BACKUP LOG Local_AW TO DISK = N'''
    + @dir + N'LOC_LOG_TAIL.trn'' WITH NORECOVERY, INIT, FORMAT, CHECKSUM;';
    EXEC (@sql);
    -- scripts 45 + 91 on Remote: FULL + every log + tail-log, then recover
    DECLARE @move NVARCHAR(MAX),
    @bk NVARCHAR(400) = @dir + N'LOC_FULL.bak';
    EXEC #move_for @backup = @bk,
    @target = N'Remote_AW',
    @move = @move OUTPUT;
    SET @sql = N'RESTORE DATABASE Remote_AW FROM DISK = N''' + @bk + N''' WITH NORECOVERY, ' + @move + N';';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Remote_AW FROM DISK = N''' + @dir + N'LOC_LOG_1.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Remote_AW FROM DISK = N''' + @dir + N'LOC_LOG_2.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Remote_AW FROM DISK = N''' + @dir + N'LOC_LOG_TAIL.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    RESTORE DATABASE Remote_AW WITH RECOVERY;
    ALTER DATABASE Remote_AW SET MULTI_USER;
    SELECT name,
    state_desc,
    user_access_desc
    FROM sys.databases
    WHERE name IN ( N'Local_AW', N'Remote_AW' ); -- Local_AW RESTORING, Remote_AW ONLINE
    GO
    /* ---------- 3. The weekend on Remote: rows, and the backups Remote takes (FULL, DIFF, LOG) ---------- */
    DECLARE @dir NVARCHAR(400) =
    (
    SELECT v FROM #sim WHERE k = 'dir'
    ),
    @sql NVARCHAR(MAX);
    INSERT Remote_AW.dbo.Movement
    (
    note,
    written_on
    )
    VALUES
    ('Remote: Friday night test', 'Remote');
    SET @sql = N'BACKUP DATABASE Remote_AW TO DISK = N''' + @dir + N'REM_FULL_1.bak'' WITH INIT, FORMAT, CHECKSUM;';
    EXEC (@sql); -- CUTOVER step 8
    INSERT Remote_AW.dbo.Movement
    (
    note,
    written_on
    )
    VALUES
    ('Remote: Saturday', 'Remote');
    SET @sql = N'BACKUP LOG Remote_AW TO DISK = N''' + @dir + N'REM_LOG_1.trn'' WITH INIT, FORMAT, CHECKSUM;';
    EXEC (@sql);
    SET @sql
    = N'BACKUP DATABASE Remote_AW TO DISK = N''' + @dir
    + N'REM_DIFF_1.bak'' WITH DIFFERENTIAL, INIT, FORMAT, CHECKSUM;';
    EXEC (@sql);
    INSERT Remote_AW.dbo.Movement
    (
    note,
    written_on
    )
    VALUES
    ('Remote: Sunday, go-live', 'Remote');
    SET @sql = N'BACKUP LOG Remote_AW TO DISK = N''' + @dir + N'REM_LOG_2.trn'' WITH INIT, FORMAT, CHECKSUM;';
    EXEC (@sql);
    SET @sql = N'BACKUP DATABASE Remote_AW TO DISK = N''' + @dir + N'REM_FULL_2.bak'' WITH INIT, FORMAT, CHECKSUM;';
    EXEC (@sql); -- the 05:00 FULL
    INSERT Remote_AW.dbo.Movement
    (
    note,
    written_on
    )
    VALUES
    ('Remote: Monday morning business', 'Remote');
    SET @sql
    = N'BACKUP DATABASE Remote_AW TO DISK = N''' + @dir
    + N'REM_DIFF_2.bak'' WITH DIFFERENTIAL, INIT, FORMAT, CHECKSUM;';
    EXEC (@sql); -- a DIFF on top of the 05:00 FULL
    SET @sql = N'BACKUP LOG Remote_AW TO DISK = N''' + @dir + N'REM_LOG_3.trn'' WITH INIT, FORMAT, CHECKSUM;';
    EXEC (@sql);
    INSERT Remote_AW.dbo.Movement
    (
    note,
    written_on
    )
    VALUES
    ('Remote: last transaction before the rollback', 'Remote');
    GO
    /* ---------- 4. Monday rollback: freeze Remote, give Local only Remote's logs ---------- */
    DECLARE @dir NVARCHAR(400) =
    (
    SELECT v FROM #sim WHERE k = 'dir'
    ),
    @sql NVARCHAR(MAX);
    -- what Remote has, to compare with afterwards
    IF OBJECT_ID(N'tempdb..#remote_rows') IS NOT NULL
    DROP TABLE #remote_rows;
    SELECT id,
    note,
    written_on
    INTO #remote_rows
    FROM Remote_AW.dbo.Movement;
    -- script 93: tail-log WITH NORECOVERY on Remote -> Remote_AW RESTORING
    SET @sql
    = N'ALTER DATABASE Remote_AW SET SINGLE_USER WITH ROLLBACK IMMEDIATE; ' + N'BACKUP LOG Remote_AW TO DISK = N'''
    + @dir + N'REM_LOG_TAIL.trn'' WITH NORECOVERY, INIT, FORMAT, CHECKSUM;';
    EXEC (@sql);
    -- script 95 on Local: Remote's LOGs only (REM_FULL_1, REM_DIFF_1, REM_FULL_2, REM_DIFF_2 are NOT used), then recover
    SET @sql = N'RESTORE LOG Local_AW FROM DISK = N''' + @dir + N'REM_LOG_1.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Local_AW FROM DISK = N''' + @dir + N'REM_LOG_2.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Local_AW FROM DISK = N''' + @dir + N'REM_LOG_3.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Local_AW FROM DISK = N''' + @dir + N'REM_LOG_TAIL.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    RESTORE DATABASE Local_AW WITH RECOVERY;
    ALTER DATABASE Local_AW SET MULTI_USER;
    GO
    /* ---------- 5. Check ---------- */
    SELECT name,
    state_desc,
    user_access_desc
    FROM sys.databases
    WHERE name IN ( N'Local_AW', N'Remote_AW' ); -- Local_AW ONLINE, Remote_AW RESTORING
    SELECT id,
    note,
    written_on
    FROM Local_AW.dbo.Movement
    ORDER BY id; -- 4 rows written on Local, 5 on Remote
    SELECT CASE
    WHEN NOT EXISTS
    (
    SELECT id,
    note,
    written_on
    FROM #remote_rows
    EXCEPT
    SELECT id,
    note,
    written_on
    FROM Local_AW.dbo.Movement
    )
    AND NOT EXISTS
    (
    SELECT id,
    note,
    written_on
    FROM Local_AW.dbo.Movement
    EXCEPT
    SELECT id,
    note,
    written_on
    FROM #remote_rows
    ) THEN
    'IDENTICAL: Local has everything Remote had, from logs only'
    ELSE
    'DIFFERENT'
    END AS result;
    GO
    /* ---------- 6. What SQL Server recorded: each backup's LSN range and which FULL each DIFF is based on ---------- */
    DECLARE @dir NVARCHAR(400) =
    (
    SELECT v FROM #sim WHERE k = 'dir'
    );
    WITH files
    AS (SELECT file_name
    FROM
    (
    VALUES
    (N'LOC_FULL.bak'),
    (N'LOC_LOG_1.trn'),
    (N'LOC_LOG_2.trn'),
    (N'LOC_LOG_TAIL.trn'),
    (N'REM_FULL_1.bak'),
    (N'REM_LOG_1.trn'),
    (N'REM_DIFF_1.bak'),
    (N'REM_LOG_2.trn'),
    (N'REM_FULL_2.bak'),
    (N'REM_DIFF_2.bak'),
    (N'REM_LOG_3.trn'),
    (N'REM_LOG_TAIL.trn')
    ) AS v (file_name) ),
    h
    AS (SELECT f.file_name,
    x.*
    FROM files AS f
    CROSS APPLY
    (
    SELECT TOP (1)
    s.backup_set_id,
    s.database_name,
    s.type,
    s.backup_set_uuid,
    s.differential_base_guid,
    s.first_lsn,
    s.last_lsn,
    s.database_backup_lsn
    FROM msdb.dbo.backupset AS s
    JOIN msdb.dbo.backupmediafamily AS m
    ON m.media_set_id = s.media_set_id
    WHERE m.physical_device_name = @dir + f.file_name
    ORDER BY s.backup_set_id DESC
    ) AS x )
    SELECT h.file_name,
    h.database_name,
    CASE h.type
    WHEN 'D' THEN
    'FULL'
    WHEN 'I' THEN
    'DIFF'
    WHEN 'L' THEN
    'LOG'
    END AS kind,
    h.first_lsn,
    h.last_lsn,
    h.database_backup_lsn,
    base.file_name AS diff_based_on -- REM_DIFF_1 -> REM_FULL_1, REM_DIFF_2 -> REM_FULL_2
    FROM h
    LEFT JOIN h AS base
    ON h.type = 'I'
    AND base.type = 'D'
    AND base.backup_set_uuid = h.differential_base_guid
    ORDER BY h.backup_set_id;
    -- the row check used by tests A, C and D: Rebuild_AW against what Remote had before its tail-log
    DELETE #sim
    WHERE k = 'cmp';
    INSERT #sim
    VALUES
    ('cmp',
    N'SELECT ''{test}'' AS test,
    CASE WHEN NOT EXISTS (SELECT id, note, written_on FROM #remote_rows EXCEPT SELECT id, note, written_on FROM Rebuild_AW.dbo.Movement)
    AND NOT EXISTS (SELECT id, note, written_on FROM Rebuild_AW.dbo.Movement EXCEPT SELECT id, note, written_on FROM #remote_rows)
    THEN ''IDENTICAL to Remote'' ELSE ''DIFFERENT'' END AS result,
    (SELECT COUNT(*) FROM Rebuild_AW.dbo.Movement) AS rows_found;');
    GO
    /* ---------- 7. Test A: a DIFF tried on the frozen copy (expected to FAIL), then the logs as normal ---------- */
    -- The real-life question: on Sunday someone restores a DIFF from S3 onto Wyton's RESTORING copy by mistake. What happens?
    DECLARE @dir NVARCHAR(400) =
    (
    SELECT v FROM #sim WHERE k = 'dir'
    ),
    @move NVARCHAR(MAX),
    @bk NVARCHAR(400),
    @sql NVARCHAR(MAX);
    PRINT N'===== Test A: build a copy of the frozen Local (LOC_FULL + LOC_LOG_1, 2, TAIL), as Local_AW was after section 2 =====';
    SET @bk = @dir + N'LOC_FULL.bak';
    EXEC #move_for @backup = @bk,
    @target = N'Rebuild_AW',
    @move = @move OUTPUT;
    SET @sql = N'RESTORE DATABASE Rebuild_AW FROM DISK = N''' + @bk + N''' WITH NORECOVERY, REPLACE, ' + @move + N';';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'LOC_LOG_1.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'LOC_LOG_2.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'LOC_LOG_TAIL.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    PRINT N'===== Test A: now REM_DIFF_2 on it. Expected: Msg 3136 (its base is REM_FULL_2, the copy was built from LOC_FULL) =====';
    SET @sql = N'RESTORE DATABASE Rebuild_AW FROM DISK = N''' + @dir + N'REM_DIFF_2.bak'' WITH NORECOVERY;';
    EXEC (@sql);
    SELECT 'Test A, after the failed DIFF' AS test,
    name,
    state_desc
    FROM sys.databases
    WHERE name = N'Rebuild_AW'; -- still RESTORING
    PRINT N'===== Test A: Remote''s logs, as in section 4. Expected: they apply, the failed DIFF did no harm =====';
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'REM_LOG_1.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'REM_LOG_2.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'REM_LOG_3.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'REM_LOG_TAIL.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    RESTORE DATABASE Rebuild_AW WITH RECOVERY;
    ALTER DATABASE Rebuild_AW SET MULTI_USER;
    SET @sql = REPLACE(
    (
    SELECT v FROM #sim WHERE k = 'cmp'
    ),
    N'{test}',
    N'Test A'
    );
    EXEC (@sql);
    GO
    /* ---------- 8. Test B: FULL_2 + DIFF_1, the wrong pair (expected to FAIL) ---------- */
    DECLARE @dir NVARCHAR(400) =
    (
    SELECT v FROM #sim WHERE k = 'dir'
    ),
    @move NVARCHAR(MAX),
    @bk NVARCHAR(400),
    @sql NVARCHAR(MAX);
    PRINT N'===== Test B: REM_FULL_2 + REM_DIFF_1. Expected: Msg 3136 at REM_DIFF_1 (its base is REM_FULL_1) =====';
    SET @bk = @dir + N'REM_FULL_2.bak';
    EXEC #move_for @backup = @bk,
    @target = N'Rebuild_AW',
    @move = @move OUTPUT;
    SET @sql = N'RESTORE DATABASE Rebuild_AW FROM DISK = N''' + @bk + N''' WITH NORECOVERY, REPLACE, ' + @move + N';';
    EXEC (@sql);
    SET @sql = N'RESTORE DATABASE Rebuild_AW FROM DISK = N''' + @dir + N'REM_DIFF_1.bak'' WITH NORECOVERY;';
    EXEC (@sql);
    SELECT 'Test B, after the failed DIFF' AS test,
    name,
    state_desc
    FROM sys.databases
    WHERE name = N'Rebuild_AW'; -- RESTORING, left for test C to replace
    GO
    /* ---------- 9. Test C: the fallback, latest FULL + its DIFF + the logs after it (expected to WORK) ---------- */
    -- The real-life case: Wyton's frozen copy is lost, so it is rebuilt from EC2's backups.
    -- REM_LOG_3 starts before REM_DIFF_2 and ends after it: it still applies.
    DECLARE @dir NVARCHAR(400) =
    (
    SELECT v FROM #sim WHERE k = 'dir'
    ),
    @move NVARCHAR(MAX),
    @bk NVARCHAR(400),
    @sql NVARCHAR(MAX);
    PRINT N'===== Test C: REM_FULL_2 + REM_DIFF_2 + REM_LOG_3 + REM_LOG_TAIL. Expected: works, identical to Remote =====';
    SET @bk = @dir + N'REM_FULL_2.bak';
    EXEC #move_for @backup = @bk,
    @target = N'Rebuild_AW',
    @move = @move OUTPUT;
    SET @sql = N'RESTORE DATABASE Rebuild_AW FROM DISK = N''' + @bk + N''' WITH NORECOVERY, REPLACE, ' + @move + N';';
    EXEC (@sql);
    SET @sql = N'RESTORE DATABASE Rebuild_AW FROM DISK = N''' + @dir + N'REM_DIFF_2.bak'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'REM_LOG_3.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'REM_LOG_TAIL.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    RESTORE DATABASE Rebuild_AW WITH RECOVERY;
    ALTER DATABASE Rebuild_AW SET MULTI_USER;
    SET @sql = REPLACE(
    (
    SELECT v FROM #sim WHERE k = 'cmp'
    ),
    N'{test}',
    N'Test C'
    );
    EXEC (@sql);
    GO
    /* ---------- 10. Test D: older FULL + its DIFF + every log (expected to WORK, LOG_1 refused as too early) ---------- */
    -- Shows that REM_FULL_2 in between does not break the chain from REM_FULL_1, and that a log ending
    -- before the DIFF is refused harmlessly (script 95 skips Msg 4326 the same way).
    DECLARE @dir NVARCHAR(400) =
    (
    SELECT v FROM #sim WHERE k = 'dir'
    ),
    @move NVARCHAR(MAX),
    @bk NVARCHAR(400),
    @sql NVARCHAR(MAX);
    PRINT N'===== Test D: REM_FULL_1 + REM_DIFF_1 + REM_LOG_1, 2, 3, TAIL. Expected: Msg 4326 for REM_LOG_1 (too early), the rest apply =====';
    SET @bk = @dir + N'REM_FULL_1.bak';
    EXEC #move_for @backup = @bk,
    @target = N'Rebuild_AW',
    @move = @move OUTPUT;
    SET @sql = N'RESTORE DATABASE Rebuild_AW FROM DISK = N''' + @bk + N''' WITH NORECOVERY, REPLACE, ' + @move + N';';
    EXEC (@sql);
    SET @sql = N'RESTORE DATABASE Rebuild_AW FROM DISK = N''' + @dir + N'REM_DIFF_1.bak'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'REM_LOG_1.trn'' WITH NORECOVERY;';
    EXEC (@sql); -- Msg 4326 expected
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'REM_LOG_2.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'REM_LOG_3.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    SET @sql = N'RESTORE LOG Rebuild_AW FROM DISK = N''' + @dir + N'REM_LOG_TAIL.trn'' WITH NORECOVERY;';
    EXEC (@sql);
    RESTORE DATABASE Rebuild_AW WITH RECOVERY;
    ALTER DATABASE Rebuild_AW SET MULTI_USER;
    SET @sql = REPLACE(
    (
    SELECT v FROM #sim WHERE k = 'cmp'
    ),
    N'{test}',
    N'Test D'
    );
    EXEC (@sql);
    -- file names of the three copies: logical AW_sim_data_n / AW_sim_log_n everywhere, physical <database>_<file_id>
    SELECT DB_NAME(database_id) AS database_name,
    type_desc,
    name AS logical_name,
    physical_name
    FROM sys.master_files
    WHERE database_id IN ( DB_ID(N'Local_AW'), DB_ID(N'Remote_AW'), DB_ID(N'Rebuild_AW'))
    ORDER BY database_name,
    file_id;
    GO
    /* ---------- 11. Clean-up, when you are done (not run by F5: remove the comment marks) ----------
    DROP DATABASE [Local_AW];
    DROP DATABASE [Remote_AW]; -- RESTORING: DROP works on it as it is
    DROP DATABASE [Rebuild_AW];
    -- and delete the folder AW_rollback_sim under the default backup folder
    */
  • Using Performance Monitor Lite with Local LLMs

    The one and only Erik Darling (homepage) is doing his best to help us to make our lives easier by providing a fully fledged monitoring solution (two, actually) for SQL Server, all this for free. Yes, FREE: https://github.com/erikdarlingdata/performancemonitor. Due to the nature of my job I can only use the Lite version, not the fully fledged one (so only one monitoring solution, at least for me).

    Not only that, but the solution(s) are documented: https://www.youtube.com/playlist?list=PLt4QZ-7lfQieiFUIuviNlyK4gcycvFiAI. And one of the videos is even showing you how to use AI to query your servers. Except I personally cannot do that. So here is my setup:

    LMStudio: installed locally on a DELL PRECISION, targeting my (not really) local LLMs on a MacBook Pro via LM Link. Dead easy to set up, not even going there, especially since your setup will most likely have your LLMs locally and not on a remote machine (oh, the irony) like I do.
    VS Code with LM Studio for Copilot Chat (Dan Lambiase) – updated fairly regularly, dead easy to set up.
    Not really related to this, but I have Continue as well, for chatting, rewrites, etc. (https://continue.dev/) – except they are now part of Cursor, so I have no idea where this goes.

    Now for the fun part: Erik shows you how to use AI to query your servers with Claude. That is a no-go for me, for both financial and, more importantly, sensitive data reasons. So I tried to point a different tool/extension to the MCP server. Quick Google search and Cline seems to be the one to choose (https://marketplace.visualstudio.com/items?itemName=saoudrizwan.claude-dev).
    I have no idea why, but it would not install for me, so eventually I downloaded the *.vsix file and was able to install it that route.
    This is how it looks as of now:

    Now you need to point Cline to the MCP server (the bottom icon, fyi). Erik is more than kind, will even give you the command to run in the command prompt for it to work.

    Click The Cop_y Setup Command (don’t ask) and run the command in the console:
    claude mcp add --transport http --scope user sql-monitor http://localhost:5151/.
    Except no, it doesn’t work. Because you need Claude Code, which I am not willing to pay for. So quick search again, and it seems you don’t need Claude, you can set up the config file for Cline directly (disregard the two MCP servers set up, we only care about sql-monitor):

    {
    "mcpServers": {
    "sql-monitor": {
    "autoApprove": [],
    "disabled": false,
    "timeout": 60,
    "type": "streamableHttp",
    "url": "http://localhost:5151"
    }
    }
    }

    And the result:

    No bueno. Back to Google search – it turns out that you CAN install Claude Code for free. You just cannot really use it – perhaps you can, when I tried it threw me to a login page where everything seemed to be paid. Anyway, in Powershell, run: irm https://claude.ai/install.ps1 | iex. Once complete, run again:
    claude mcp add --transport http --scope user sql-monitor http://localhost:5151/. This time it works.

    For Cline, I deleted all the servers I created and recreated a new one with the above settings and presto!, it works now.

    Topics not covered:

    • how to set up the rest of the tools
    • how to set up VS Code to use a local LLM and not a frontier model
    • the performance (readable but very slow due to limited performance of the local machines, etc).

    My two cents:

    • if you have the money to invest, go with frontier models as long as you are not pushing more than 200 USD/month – anything beyond that and the economics will start to fail, at least in my case. Of course, this assumes you are not working with sensitive data
    • I am not a huge fan of agentic AI, not in the current form – it fails spectacularly, and it fails on your time and dime
    • if you have money to burn, wait for the new Mac Studio or similar stuff – something tells me it will push past beyond 15K USD for the ones that can host decent models. But I deeply distrust the learning process of any LLM as of now, not to mention the “guardrails”; as of August 2026 all the major frontier providers reported their agents going rogue and creating havoc online. In a normal world this is a felony punishable by law. These days, is a badge of honor. Thanks but no thanks.
  • FOR XML PATH, STRING_AGG and AI

    For the AI warriors out there – I was rewriting a bunch of stored procedures (270+, to be more precise), so naturally AI comes into play (QWEN Coder Next 80B at 8 bit and GPT-OSS 120B MXFP4 – not as precise, but works good enough. Yes, I need to work with local models because of the very sensitive data I get to see). I usually end up with stored_proc_name and stored_proc_name_V1, where the _V1 is chosen from a bunch of different paths I explore. In many cases I see the AI telling me to replace FOR XML PATH with STRING_AGG function.

    Now, consider the following scenario.

    The XML PATH (“old”) stored procedure:

    USE AdventureWorks;
    GO
    
    CREATE OR ALTER PROCEDURE dbo.usp_Performance_ForXmlPath
    AS
    BEGIN
        SET NOCOUNT ON;
    
        DECLARE @StartTime DATETIME2(7) = SYSDATETIME();
    
        SELECT soh.SalesOrderID,
               STUFF(
                        (
                            SELECT N', ' + p2.Name
                            FROM Sales.SalesOrderDetail AS sod2
                                INNER JOIN Production.Product AS p2
                                    ON p2.ProductID = sod2.ProductID
                            WHERE sod2.SalesOrderID = soh.SalesOrderID
                            ORDER BY p2.Name
                            FOR XML PATH(''), TYPE
                        ).value('.', 'nvarchar(max)'),
                        1,
                        2,
                        N''
                    ) AS ProductList
        FROM Sales.SalesOrderHeader AS soh
        ORDER BY soh.SalesOrderID DESC;
    END;
    GO

    The STRING_AGG (“new”) procedure (basically a rewrite of the “old” XML PATH procedure, as rewritten by AI:

    USE AdventureWorks;
    GO

    CREATE OR ALTER PROCEDURE dbo.usp_Performance_StringAgg
    AS
    BEGIN
    SET NOCOUNT ON;

    DECLARE @StartTime DATETIME2(7) = SYSDATETIME();

    SELECT sod.SalesOrderID,
    STRING_AGG(CONVERT(NVARCHAR(MAX), p.Name), N', ') WITHIN GROUP(ORDER BY p.Name) AS ProductList
    FROM Sales.SalesOrderDetail AS sod
    INNER JOIN Production.Product AS p
    ON p.ProductID = sod.ProductID
    GROUP BY sod.SalesOrderID
    ORDER BY sod.SalesOrderID DESC;
    END;
    GO

    A side note for the ones too lazy to run the scripts: they simply return the products as a product list for each invoice. Yes, they return the same result. Moving on.

    Now, for the big question, assuming your prod server is a highly concurrent Azure MI Business Critical tier, which of the above stored procedures should make it to prod? And, more importantly, WHY?

  • Find and Change (N)VARCHAR(MAX) to (N)VARCHAR(XXX)

    I know, I know, everything I do is rushed and not properly explained, apologies for that. Anyway.
    During some investigation, I came across some badly designed tables where most of the columns meant to hold character data were NVARCHAR(MAX), all this while the maximum length of the strings were something in the area of 30-50 characters. It has been widely documented why this is a bad idea in terms of performance, so I will only put a script in here that will attempt to categorize them from 1 to 255, 255 to 512, 512 to 1024, etc.

    SET NOCOUNT ON;
    IF OBJECT_ID('tempdb..#MaxVarChar') IS NOT NULL
    DROP TABLE #MaxVarChar;
    CREATE TABLE #MaxVarChar
    (
    SchemaName NVARCHAR(128) COLLATE DATABASE_DEFAULT,
    TableName NVARCHAR(128) COLLATE DATABASE_DEFAULT,
    ColumnName NVARCHAR(128) COLLATE DATABASE_DEFAULT,
    TypeName SYSNAME COLLATE DATABASE_DEFAULT,
    MaxLen INT NOT NULL
    );
    DECLARE @sql NVARCHAR(MAX) = N'';
    ;WITH VarMaxCols AS
    (
    SELECT
    s.name AS SchemaName,
    t.name AS TableName,
    c.name AS ColumnName,
    ty.name AS TypeName
    FROM sys.columns c
    JOIN sys.types ty
    ON c.user_type_id = ty.user_type_id
    JOIN sys.tables t
    ON c.object_id = t.object_id
    JOIN sys.schemas s
    ON t.schema_id = s.schema_id
    WHERE ty.name IN (N'varchar', N'nvarchar')
    AND c.max_length = -1
    AND t.is_ms_shipped = 0
    )
    SELECT
    @sql = @sql + N'
    INSERT INTO #MaxVarChar
    (
    SchemaName,
    TableName,
    ColumnName,
    TypeName,
    MaxLen
    )
    SELECT
    ' + QUOTENAME(SchemaName, '''') + N',
    ' + QUOTENAME(TableName, '''') + N',
    ' + QUOTENAME(ColumnName, '''') + N',
    ' + QUOTENAME(TypeName, '''') + N',
    ISNULL(
    MAX(
    ISNULL(' +
    CASE
    WHEN TypeName = N'nvarchar' THEN
    N'DATALENGTH(' + QUOTENAME(ColumnName) + N') / 2'
    ELSE
    N'DATALENGTH(' + QUOTENAME(ColumnName) + N')'
    END
    + N', 0)
    ),
    0
    )
    FROM ' + QUOTENAME(SchemaName) + N'.' + QUOTENAME(TableName) + N';'
    FROM VarMaxCols
    ORDER BY
    SchemaName,
    TableName,
    ColumnName;
    IF LEN(@sql) > 0
    EXEC sys.sp_executesql @sql;
    ;WITH VarMaxCols AS
    (
    SELECT
    s.name AS SchemaName,
    t.name AS TableName,
    c.name AS ColumnName,
    ty.name AS TypeName,
    c.is_nullable,
    c.collation_name
    FROM sys.columns c
    JOIN sys.types ty
    ON c.user_type_id = ty.user_type_id
    JOIN sys.tables t
    ON c.object_id = t.object_id
    JOIN sys.schemas s
    ON t.schema_id = s.schema_id
    WHERE ty.name IN (N'varchar', N'nvarchar')
    AND c.max_length = -1
    AND t.is_ms_shipped = 0
    )
    SELECT
    N'ALTER TABLE '
    + QUOTENAME(vc.SchemaName)
    + N'.'
    + QUOTENAME(vc.TableName)
    + N' ALTER COLUMN '
    + QUOTENAME(vc.ColumnName)
    + N' '
    + UPPER(vc.TypeName)
    + N'('
    + CASE
    WHEN vc.TypeName = N'nvarchar' THEN
    CASE
    WHEN m.MaxLen <= 255 THEN N'255'
    WHEN m.MaxLen <= 512 THEN N'512'
    WHEN m.MaxLen <= 1024 THEN N'1024'
    WHEN m.MaxLen <= 2048 THEN N'2048'
    ELSE N'4000'
    END
    WHEN vc.TypeName = N'varchar' THEN
    CASE
    WHEN m.MaxLen <= 255 THEN N'255'
    WHEN m.MaxLen <= 512 THEN N'512'
    WHEN m.MaxLen <= 1024 THEN N'1024'
    WHEN m.MaxLen <= 2048 THEN N'2048'
    WHEN m.MaxLen <= 4000 THEN N'4000'
    ELSE N'8000'
    END
    END
    + N')'
    + CASE
    WHEN vc.collation_name IS NOT NULL THEN
    N' COLLATE ' + vc.collation_name
    ELSE
    N''
    END
    + N' '
    + CASE
    WHEN vc.is_nullable = 1 THEN N'NULL'
    ELSE N'NOT NULL'
    END
    + N';' AS AlterStatement,
    m.MaxLen
    FROM VarMaxCols vc
    JOIN #MaxVarChar m
    ON m.SchemaName = vc.SchemaName COLLATE DATABASE_DEFAULT
    AND m.TableName = vc.TableName COLLATE DATABASE_DEFAULT
    AND m.ColumnName = vc.ColumnName COLLATE DATABASE_DEFAULT
    AND m.TypeName = vc.TypeName COLLATE DATABASE_DEFAULT
    WHERE
    (
    vc.TypeName = N'nvarchar'
    AND m.MaxLen <= 4000
    )
    OR
    (
    vc.TypeName = N'varchar'
    AND m.MaxLen <= 8000
    )
    ORDER BY
    vc.SchemaName,
    vc.TableName,
    vc.ColumnName;

    It basically checks the base tables for columns that have VARCHAR(MAX) or NVARCHAR(MAX) as definition and then it checks for the maximum length of the strings you have stored. Just make sure you set Results To Text (CTRL + T) and not grid and you should have the scripts generated for you.
    Of course, you must remember that the ALTER TABLE ... ALTER COLUMN will fail if the column is part of an index, constraint, etc.
    You also must take into account that if you have a ton of columns that qualify, a ton of ALTER statements will be generated, which is not ideal, to put it mildly.

    One caveat here: my original script transformed all the columns into NVARCHAR(XXX) so I could align them with the rest of the project. I ran it through ChatGPT and it modified it to leave the columns in their original data type (VARCHAR or NVARCHAR). So make sure you test it before even thinking to use it on prod databases.
    Just remember some of your columns might have data that already goes beyond the limits you want to set, so they will not be found in the final set of ALTER statements.
    DO NOT DO ANY CHANGES UNTIL YOU TALK TO YOUR DEV TEAM!