I'm not sure about the keyword database in the error message, but I do spot problems:
You concatenate USE
and the databasename without a space: USENAV01
doesn't work. You should use 'USE ' + QUOTENAME(@DBName)
.
Secondly, I don't know what the intention is, but if you do EXECUTE ('USE ' + @DBName);
followed by other (dynamic) queries, the following queries are executed on your current connection. In other words, the USE XXX
doesn't matter for the following queries.
Thirdly, as mentioned by Jesse in below comment; if you have more than one database with a name like '%NAV%'
(which your question suggests), your code is only executed for one of those databases. Which one that will be is unpredictable without an order by
. If you want to execute code for all relevant databases, you have to loop through them.