I have a number of databases on which I should run the same SQL file. The database names can be found in a table in another database. I was wondering if I can automate this somehow to avoid changing database manually and running the script. I'm trying to make following script working (in sqlcmd
mode):
:On Error Exit
declare @statement nvarchar(MAX), @dbname nvarchar(255)
declare NameList cursor for
select database_name from databases where type ='s'
OPEN NameList
FETCH NEXT FROM NameList
INTO @dbname
WHILE @@FETCH_STATUS = 0
BEGIN
SET @statement = N'USE '+@dbname+N'
GO'
EXEC dbo.sp_executesql @statement
:r C:\temp\check_db.sql
GO
FETCH NEXT FROM NameList INTO @dbname
END
CLOSE NameList
DEALLOCATE NameList
The idea is to go through the list of databases and use USE <DB>
statement to change the current database to one fetched from the list, then run the script from SQL file.
I'm getting error Incorrect syntax near <some point in SQL file>.
which points a row in the SQL file thus I'm concluding that USE <DB>
is not changing the current database for the SQL file.