查询SQL Server 2012数据库实例中的所有视图

时间:2014-10-03 18:29:36

标签: tsql sql-server-2012

我遇到的问题是,下面的查询只是从我连接的当前数据库中选择视图,而不是全部。反正有没有使用sp_MSForEachDB

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 个答案:

答案 0 :(得分: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

修改

您可以在USE前面附加GRANT

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