The easiest way to achieve this is what Viorel-1 stated above -
Viorel-1 · 3 hours ago
There is an internal sp_MSforeachdb, and maybe you can use it:
https://learn.microsoft.com/en-us/answers/search.html?q=sp_MSforeachdb
https://www.bing.com/search?q=sp_MSforeachdb
Or use PowerShell with the module dbatools and execute it from outside SQL Server...
Get-DbaDatabase -SqlInstance "server1" | Invoke-DbaQuery -File "C:\scripts\sql\rebuild.sql"