I am not very experienced with T-SQL and feel this can be done better. The script changes ownership of all "user" (non-system) databases to sa.
Usage of a dynamic SQL expression seems unavoidable to me. Could I at least iterate the table names in a more elegant way — imperative code looks like a code smell in a SQL script. Nested query in the while loop absolutely hurts my eyes...
How to rewrite this script to be more idiomatic?
DROP TABLE IF EXISTS #databaseNames;
SELECT name
INTO #databaseNames
FROM master.sys.databases
WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')
DECLARE @tableCount INTEGER
SELECT @tableCount = COUNT(*) FROM #databaseNames
DECLARE @tableNumber INTEGER
SET @tableNumber = 1
WHILE @tableNumber <= @tableCount
BEGIN
DECLARE @tableName VARCHAR(1024)
SELECT @tableName = name FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY name ASC) AS rowNumber,
name
FROM #databaseNames
) numberedDatabaseNames
WHERE rowNumber = @tableNumber
EXEC('ALTER AUTHORIZATION ON database::' + @tableName + ' to sa;')
SET @tableNumber = @tableNumber + 1
END;