我遇到的问题是,下面的查询只是从我连接的当前数据库中选择视图,而不是全部。反正有没有使用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
答案 0 :(得分:1)
当EXEC
语句执行字符串时,该字符串将作为自己的自包含批处理执行。因此,USE dbname
不会影响EXEC
之外的查询。
我构建一个这样的查询语句SELECT 'GRANT SELECT ON [' + SCHEMA_NAME(schema_id) + '].[' + name + '] TO [account]' FROM [master].SYS.VIEWS V;
,其中数据库名称在SYS.VIEWS之前插入。
见下文:
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;'