It's worth mentioning that this errored for me due to a couple of databases having a numeric beginning (123abc). Putting the database names into brackets where they are text strings will fix this. ex. ALTER DATABASE [@dbname] SET AUTO_CLOSE OFF
ALTER DATABASE [@dbname] SET AUTO_CLOSE OFF