I want to detect databases beginning with 'NAV'in a MS SQL DB. I tried it with this code:
DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE' + @DBName);
But I got the error message:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'Database'.
Do know what is wrong there?
Put a space after USE and put brackets around the database name:
DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + @DBName + ']');