使用带动态模式名​​称的select查询设置变量

时间:2016-05-09 11:47:30

标签: sql sql-server

我正在尝试将变量设置为查询结果。我的问题是下面的代码在while循环中运行& schemaName总是与众不同。

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

如何设置schemaName as variable以使其在while循环中可以是动态的。

1 个答案:

答案 0 :(得分:1)

这样的事情会有所帮助:

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