2

我有这个查询

SELECT 'GRANT SELECT ON ' + TABLE_NAME + ' TO '+ @UserName
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'BASE TABLE' AND 
TABLE_NAME LIKE 'aspnet%'

结果如下:

GRANT SELECT ON aspnet_Applications TO user04
GRANT SELECT ON aspnet_Membership TO user04
GRANT SELECT ON aspnet_Paths TO user04
GRANT SELECT ON aspnet_PersonalizationAllUsers TO user04
GRANT SELECT ON aspnet_PersonalizationPerUser TO user04
GRANT SELECT ON aspnet_Profile TO user04
GRANT SELECT ON aspnet_Roles TO user04
GRANT SELECT ON aspnet_SchemaVersions TO user04

我想在这个结果中运行所有的选择查询。我怎样才能做到这一点?

4

2 回答 2

1
DECLARE @Sql NVARCHAR(MAX)
SET @Sql = ''

SELECT @Sql = @Sql + 'GRANT SELECT ON ' + TABLE_NAME + ' TO '+ @UserName + '
' -- Newline to keep statements from being just one long line.
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'BASE TABLE' AND 
TABLE_NAME LIKE 'aspnet%'

-- Print it first to double-check that it looks right before running.
PRINT @Sql

-- After you've validated it with print, run it.
EXEC sp_executeSql @Sql
于 2012-06-08T18:48:06.917 回答
0

我解决了,记得在 GRANT 之前有一个空间。

    DECLARE @Sql NVARCHAR(MAX)
SET @Sql = ''
SELECT @Sql =@Sql + ' GRANT SELECT ON ' + TABLE_NAME + ' TO '+ @UserName +''
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_TYPE = 'BASE TABLE' AND 
TABLE_NAME LIKE 'aspnet%'
PRINT @Sql
EXEC sp_executeSql @Sql
于 2012-06-09T03:48:59.507 回答