如何在变量中获取值:
DECLARE @Query NVARCHAR(MAX)
DECLARE @CurrentModuleUsers INT
SET @Query = 'SELECT @CurrentModuleUsers = Count(UR.UserId)'+
' FROM [dbo].[aspnet_UsersInRoles] AS UR '+
' INNER JOIN [dbo].[aspnet_Roles] AS R ON UR.RoleId = R.RoleId '+
' INNER JOIN [dbo].[aspnet_Users] AS U ON UR.UserId = U.UserId '+
' WHERE LOWER(RoleName) IN ( ' +
' SELECT LOWER([Role]) '+
' FROM ADMIN_ROLEACCESS '+
')'
EXEC(@query)
print @CurrentModuleUsers
错误:
必须声明标量变量" @ CurrentModuleUsers"。
请帮我解决这个问题。
答案 0 :(得分:3)
使用sp_executesql而不是exec()
exec sp_executesql @query, N'@CurrentModuleUsers INT OUTPUT', @CurrentModuleUsers OUTPUT
为什么需要在这里使用动态SQL?我不认为有必要这样做
答案 1 :(得分:0)
在您的情况下不需要动态sql。您可以使用简单的选择直接获取计数。
DECLARE @CurrentModuleUsers INT
SELECT @CurrentModuleUsers = Count(UR.UserId)
FROM [dbo].[aspnet_UsersInRoles] AS UR
INNER JOIN [dbo].[aspnet_Roles] AS R ON UR.RoleId = R.RoleId
INNER JOIN [dbo].[aspnet_Users] AS U ON UR.UserId = U.UserId
WHERE LOWER(RoleName) IN (
SELECT LOWER([Role])
FROM ADMIN_ROLEACCESS
)
PRINT @CurrentModuleUsers