I have a strange problem with my nested cursors and I have no idea what it's all about.
Here's my T-SQL code:
declare @dbname varchar(50)
declare @servername varchar(50)
declare srv cursor for select servername from test.dbo.servers
declare @str varchar(200)
truncate table test.dbo.temp
open srv
fetch next from srv into @servername
while @@fetch_status = 0
begin
set @str = 'Data Source='+@servername+';Integrated Security=SSPI'
declare db cursor for select name from opendatasource('SQLNCLI', @str).master.dbo.sysdatabases
open db
fetch next from db into @dbname
while @@fetch_status = 0
begin
insert test.dbo.temp (dbname, servername) values (@dbname, @servername)
fetch next from db into @dbname
end
fetch next from srv into @servername
close db
deallocate db
end
close srv
deallocate srv
It gives me next error message:
Incorrect syntax near '@str'. [SQLSTATE 42000] (Error 102)
Looks like the problem is in giving the variable as a parameter to opendatasource function. But why? And how to avoid this problem?