• DECLARE @databasename sysname

    is sufficient. nvarchar(max) looks a little bit overwhelmed