如何将另一个select的结果插入到添加了额外列值的新表中?

时间:2014-04-18 13:47:49

标签: sql tsql asp.net-membership

在ASP.NET UsersInRoles Membership表中,我有aspnet_UsersUserId等等,我有aspnet_RolesRoleIdRoleName等等,我有一个表将aspnet_UsersInRolesRoleIdUserId联系在一起。

现在我想给所有没有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>

1 个答案:

答案 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;