2014-10-03 94 views
0

我遇到問題,下面的查詢只從當前連接到的數據庫中選擇視圖,而不是全部。無論如何要做到這一點,而不是使用sp_MSForEachDB查詢SQL Server 2012數據庫實例中的所有視圖

DECLARE @useText VARCHAR(500) 
DECLARE @viewNM VARCHAR(500) 
DECLARE @schemaNM VARCHAR(500) 
DECLARE @dbNM VARCHAR(500) 
DECLARE @sqlCmd varchar(4000) 

DECLARE DBCursor CURSOR GLOBAL FOR 
    SELECT NAME FROM SYS.DATABASES 

OPEN DBCursor 
FETCH NEXT FROM DBCursor INTO @dbNM 

WHILE @@FETCH_STATUS <> -1 
BEGIN 
    SET @useText = 'USE [' + @dbNM + ']' 
    EXEC(@useText) 

    DECLARE ViewCursor CURSOR FOR 
     SELECT 'GRANT SELECT ON ' + '[' + SCHEMA_NAME(schema_id) + '].[' + name + ']' + ' TO [account]' 
     FROM SYS.VIEWS V 

    OPEN ViewCursor 
    FETCH NEXT FROM ViewCursor INTO @sqlCmd 

    WHILE @@FETCH_STATUS = 0 
    BEGIN 
     PRINT(@sqlCmd) 
     FETCH NEXT FROM ViewCursor INTO @sqlCmd 
    END 

    CLOSE ViewCursor 
    DEALLOCATE ViewCursor 

    FETCH NEXT FROM DBCursor INTO @dbNM 
END 

CLOSE DBCursor 
DEALLOCATE DBCursor 

回答

1

EXEC語句執行字符串,字符串作爲其自身含有批處理執行。因此,USE dbname不會影響EXEC以外的查詢。

我構建了一個像這樣的查詢語句SELECT 'GRANT SELECT ON [' + SCHEMA_NAME(schema_id) + '].[' + name + '] TO [account]' FROM [master].SYS.VIEWS V;,其中數據庫名稱被插入到SYS.VIE​​WS之前。

見下文:

DECLARE @useText VARCHAR(500) 
DECLARE @viewNM VARCHAR(500) 
DECLARE @schemaNM VARCHAR(500) 
DECLARE @dbNM VARCHAR(500) 
DECLARE @sqlCmd varchar(4000) 

DECLARE DBCursor CURSOR GLOBAL FOR 
    SELECT NAME FROM SYS.DATABASES 

OPEN DBCursor 
FETCH NEXT FROM DBCursor INTO @dbNM 

WHILE @@FETCH_STATUS <> -1 
BEGIN 

     set @sqlCmd = 'SELECT ''GRANT SELECT ON ['' + SCHEMA_NAME(schema_id) + ''].['' + name + ''] TO [account]'' FROM [' + @dbNM + '].SYS.VIEWS V;' 

     exec(@sqlCmd); 

    FETCH NEXT FROM DBCursor INTO @dbNM 
END 

CLOSE DBCursor 
DEALLOCATE DBCursor 

編輯:

你可以在GRANT前追加USE

set @sqlCmd = 'SELECT ''USE ' + @dbNM + '; GRANT SELECT ON ['' + SCHEMA_NAME(schema_id) + ''].['' + name + ''] TO [account]'' FROM [' + @dbNM + '].SYS.VIEWS V;' 
+0

嗯,我想你可能會遇到GRANT的另一個問題。您只能授予或撤銷當前數據庫中對象的權限。 – jim31415 2014-10-03 19:33:54

相關問題