0

How can I get value in variable:

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

Error:

Must declare the scalar variable "@CurrentModuleUsers".

Please help me how to fix this.

2 Answers 2

3

use sp_executesql instead of exec()

exec sp_executesql @query, N'@CurrentModuleUsers INT OUTPUT', @CurrentModuleUsers OUTPUT

Why do you need to use dynamic sql here ? i don't see a need to do that

Sign up to request clarification or add additional context in comments.

Comments

0

There is no need of dynamic sql in your case. You can directly get the count using simple select.

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

1 Comment

True, but I am actually dealing with various different databases on the same server, database name is passed to procedure and have to build the dynamic query. Wondering if you share some idea for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.