2

I am trying to set a variable as a query result. My problem is that below code runs in a while loop & schemaName is always different.

WHILE (@i <= (SELECT MAX(idx) FROM @schema_table))

BEGIN
SET @userid = (SELECT AspNetUsers.Id
                FROM schemaName.AspNetUsers
                LEFT JOIN schemaNameAspNetUserRoles ON  AspNetUserRoles.UserId = AspNetUsers.Id 
                LEFT JOIN schemaName.AspNetRoles ON AspNetRoles.Id = AspNetUserRoles.RoleId
                WHERE AspNetRoles.Name = 'SuperAdmin')
END

How to set schemaName as variable so that it can be dynamic in the while loop.

1
  • 2
    You would have to use dynamic SQL. Commented May 9, 2016 at 11:49

1 Answer 1

1

Something like this will help:

DECLARE @sql nvarchar(4000),
        @schemaName nvarchar(200),
        @i int = 1,
        @vParams nvarchar(100)

SET @vParams = '@uid int OUTPUT'


WHILE (@i <= (SELECT MAX(idx) FROM @schema_table))

BEGIN

    SELECT @schemaName = schemaName
    FROM @schema_table
    WHERE idx = @i


    SELECT @sql = '
                    SELECT @userid = AspNetUsers.Id
                    FROM schemaName.AspNetUsers
                    LEFT JOIN schemaNameAspNetUserRoles ON  AspNetUserRoles.UserId = AspNetUsers.Id 
                    LEFT JOIN [' +@schemaName + '].AspNetRoles ON AspNetRoles.Id = AspNetUserRoles.RoleId
                    WHERE AspNetRoles.Name = ''SuperAdmin'';'


    EXEC sp_executesql @sql, @vParams, @userid=@uid OUTPUT
    -- here you hot @userid with value you need and can do something with it
    SET @i = @i + 1

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

Comments

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.