在ASP.NET UsersInRoles Membership表中,我有aspnet_Users
表UserId
等等,我有aspnet_Roles
表RoleId
和RoleName
等等,我有一个表将aspnet_UsersInRoles
与RoleId
和UserId
联系在一起。
现在我想给所有没有RoleName
" MyRoleName"的用户现有的RoleName
" RoleNameToBeGiven"。
我可以获得所有UserId
s而没有属性" MyRoleName"如下:
SELECT u.UserId FROM dbo.aspnet_Users u
INNER JOIN dbo.aspnet_UsersInRoles r
ON u.UserId = r.UserId
WHERE r.RoleId NOT IN (SELECT RoleID FROM dbo.aspnet_Roles WHERE RoleName
= 'MyRoleName')
现在,我想将此查询中获得的每个UserId
添加到aspnet_UsersInRoles
,其中RoleId
属于RoleName" RoleNameToBeGiven"。获取RoleId
" RoleNameToBeGiven"我有以下查询:
SELECT RoleId FROM dbo.aspnet_Roles
WHERE RoleName = 'RoleNameToBeGiven'
问题是:如何组合这两个查询并将第一个查询中获得的每个 UserId
插入到第二个查询中获得的aspnet_UsersInRoles" table with the
RoleId`中? / p>
答案 0 :(得分:0)
似乎我在a cursor的帮助下找到了一个可行的解决方案:
DECLARE @UserId AS uniqueidentifier;
DECLARE @RoleId AS uniqueidentifier;
DECLARE @UserCursor as CURSOR;
SET @UserCursor = CURSOR FOR
SELECT u.UserId
FROM dbo.aspnet_Users u
INNER JOIN dbo.aspnet_UsersInRoles r
ON u.UserId = r.UserId
WHERE r.RoleId NOT IN
(SELECT RoleID
FROM dbo.aspnet_Roles
WHERE RoleName = 'MyRoleName')
SET @RoleId = (
SELECT RoleId
FROM dbo.aspnet_Roles
WHERE RoleName = 'RoleNameToBeGiven'
)
OPEN @UserCursor;
FETCH NEXT FROM @UserCursor INTO @UserId
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT cast(@UserId as VARCHAR (50)) + ' ' + cast(@RoleId as VARCHAR (50));
IF NOT EXISTS (SELECT UserId, RoleId FROM dbo.aspnet_UsersInRoles
WHERE UserId = @UserId AND RoleId = @RoleId)
INSERT INTO dbo.aspnet_UsersInRoles (UserId,RoleId)
VALUES(@UserId,@RoleId);
FETCH NEXT FROM @UserCursor INTO @UserId
END
CLOSE @UserCursor;
DEALLOCATE @UserCursor;