I have a list of database connections in a table and want to iterate through them, connecting to each one within SQL Server through a script, and then execute a select statement.
Initially, I successfully executed the connection command directly for one database using
:CONNECT your_servername -U your_username -P your_password
However, when attempting to loop through multiple databases and write dynamic SQL, I encountered an error and would appreciate some expert assistance.
Here's the query I'm trying to execute: I have set mode on editor Menu --> Query --> 'SQLCMD MODE'
DECLARE @sql NVARCHAR(MAX);
DECLARE @servername NVARCHAR(100) = 'your_servername -U';
DECLARE @username NVARCHAR(100) = 'your_username';
DECLARE @password NVARCHAR(100) = '-P your_password';
SET @sql = ':CONNECT ' + @servername + ' ' + @username + ' ' + @password + '';
print @sql
EXEC sp_executesql @sql;
And here's the error message I'm receiving:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near ':'
I've tried troubleshooting it myself but haven't been able to resolve it. Could someone please help me understand what might be causing this error and how to fix it or alternate solutions?
Any guidance or suggestions would be greatly appreciated. Thank you in advance!
As others have mentioned,
:CONNECTis an sqlcmd client command and is not a valid SQL keyword.If you wish to run a query across multiple servers, you could either utilise Linked Servers, or write a batch script that executes multiple sqlcmd commands that connect to each server and execute your desired SQL queries in a loop.
If you just want to execute queries on multiple databases on the same server, you can use the
USEkeyword to change the database context the following queries will use.