我的嵌套游标有一个奇怪的问题,我不知道它是怎么回事。
这是我的 T-SQL 代码:
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
它给了我下一条错误消息:
'@str' 附近的语法不正确。[SQLSTATE 42000](错误 102)
看起来问题在于将变量作为参数提供给 opendatasource 函数。但为什么?以及如何避免这个问题?