简体   繁体   中英

Rebuilding indexes on a linked server in SQL Server 2008 R2

I'm trying to create a stored procedure which retrieves a list of my linked servers, builds a list of their databases and rebuilds any table index with a certain level of fragmentation and a certain number of pages.

The one issue I'm having is when I actually execute the rebuild command. My code is:

SET @cmd = 'ALTER INDEX' + QUOTENAME(@index) + ' ON ' + QUOTENAME(@servername) + '.' + QUOTENAME(@dbname) + '.' + QUOTENAME(@schema) + '.' + QUOTENAME(@table) +   ' REBUILD;'

EXECUTE sp_sqlexec @cmd

The error I'm getting is:

"Cannot find the object " ServerName.Databasename .dbo. IndexName " because it does not exist or you do not have permissions"

I've replaced the Server, Database and Index names but the four-part identifier displays correctly in the error message.

I'm wondering if rebuilding an index on a linked server is possible and if so, what permissions are required. Anyone else tried this sort of thing?

Thanks

EDIT:

I think I've got it. In case anyone else has this problem, try something like:

    SET @cmd = '
 EXEC(''ALTER INDEX ' + QUOTENAME(@index) + ' ON ' + @dbname + '.' + QUOTENAME(@schema) + '.' + QUOTENAME(@table) +  ' REBUILD'') AT ' + QUOTENAME(@servername) + ' '

EXECUTE sp_sqlexec @cmd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM