遍历 SQL 服务器中的服务器列表

Iterate through a list of servers in SQL Server

我有一个类似于下面的脚本并得到:

Could not find server '@CURSERVER' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.

我正在尝试从所有链接服务器获取 SQL 服务器代理作业。我认为我的链接服务器没有问题,但我可以不将服务器名称作为变量吗?

 -- Declare your array table variable  
DECLARE @SERVERS table (serverName nvarchar(50), ARRAYINDEX int identity(1,1) )  
  
-- Add values to your array table, these are the values which you need to look for in your database  
INSERT INTO @SERVERS (serverName)  
   VALUES  
('server1'), ('server2'), ('server3')
  
DECLARE @INDEXVAR INT = 1
DECLARE @TOTALCOUNT int  
DECLARE @CURSERVER nvarchar (50)  
SELECT @TOTALCOUNT= COUNT(*) FROM @SERVERS 
WHILE @INDEXVAR < @TOTALCOUNT  
BEGIN    
    -- Get value of current indexed server  
    SELECT @CURSERVER = serverName from @SERVERS where ARRAYINDEX = @INDEXVAR  
  
    -- Get details of jobs on the server  
    BEGIN  
        SELECT  
            * FROM [@CURSERVER].[msdb].[dbo].[sysjobs] 
        SET @INDEXVAR += 1
    END  
END  

您不能使用变量作为标识符(服务器名称、数据库名称、table 名称等)。相反,构造一个动态 SQL 语句并执行。

下面是一个示例,包括对原始脚本的更正和改进。

DECLARE @SERVERS table (serverName nvarchar(50), ARRAYINDEX int identity(1,1) )  
  
-- Add values to your array table, these are the values which you need to look for in your database  
INSERT INTO @SERVERS (serverName)  
   VALUES  
    ('server1'), ('server2'), ('server3');
DECLARE @TOTALCOUNT int = @@ROWCOUNT;
DECLARE @SQL nvarchar(MAX);
DECLARE @INDEXVAR INT = 1;
DECLARE @CURSERVER sysname 

WHILE @INDEXVAR <= @TOTALCOUNT  
BEGIN    
    -- Get value of current indexed server  
    SELECT @CURSERVER = serverName from @SERVERS where ARRAYINDEX = @INDEXVAR;  
  
    -- Get details of jobs on the server  
    BEGIN  
        SET @SQL = N'SELECT * FROM ' + QUOTENAME(@CURSERVER) + N'.[msdb].[dbo].[sysjobs];';
        --PRINT @SQL;
        EXEC sp_executesql @SQL;
        SET @INDEXVAR += 1;
    END;  
END;