我有这个查询
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
我想在此结果中运行所有选择查询。我怎么能这样做?
答案 0 :(得分: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
答案 1 :(得分: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