I have a server with over 100 databases linked to other database servers. These databases have views of the linked tables. I need to update the views weekly for any object changes in the linked servers, ie column adds.
I create this script to loop through all the databases and grab all the views and refresh them by doing alter view. sp_refreshview does not work with linked servers.
When I print the @sql variable, it works fine in another query window. When I try to execute the @sql variable, it gives me the following error:
Msg 111, Level 15, State 1, Line 3
'ALTER VIEW' must be the first statement in a query batch.
I think it has something to do with the LF/CR. I have tried many ways with no luck.
Any ideas?
DECLARE @command varchar(1000)
CREATE TABLE #tempViewSQL (DBName VARCHAR(255)
,ViewSQL VARCHAR(4000))
SELECT @command = 'IF ''?'' NOT IN(''master''
, ''model''
, ''msdb''
, ''tempdb''
,''pubs''
,''AuditProduction''
,''AuditProductionTest''
,''IID_Support''
,''Insurance_Files''
,''LoansAnalysis''
,''QualityAudit''
,''QualityAuditTest'')
BEGIN
USE ?
INSERT INTO #tempViewSQL
SELECT TABLE_CATALOG, replace(view_definition,''create view'',''alter view'')
FROM information_schema.views
WHERE TABLE_NAME NOT IN (''syssegments'',''sysconstraints'')
END'
EXEC sp_MSforeachdb @command
DECLARE @SQLCursor VARCHAR(2000)
DECLARE @SQL VARCHAR(2000)
DECLARE @DbName VARCHAR(255)
DECLARE MyCursor CURSOR FOR
SELECT DBName, ViewSQL FROM #tempViewSQL
OPEN MyCursor
FETCH NEXT FROM MyCursor INTO @DbName,@SQLCursor
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL = 'USE ' + @DBName + CHAR(10) + CHAR(13) + 'GO' + CHAR(10) + CHAR(13) + @SQLCursor
--PRINT (@SQL)
EXECUTE (@SQL)
FETCH NEXT FROM MyCursor INTO @DbName,@SQLCursor
END
CLOSE MyCursor
DEALLOCATE MyCursor
DROP TABLE #tempViewSQL