How to insert results from another select into new table with extra column value added?

StackOverflow https://stackoverflow.com/questions/23155488

  •  05-07-2023
  •  | 
  •  

Вопрос

In an ASP.NET UsersInRoles Membership table I have a aspnet_Users table with UserId et cetera, I have a aspnet_Roles table with RoleId and RoleName et cetera, and I have a table that joins them together called aspnet_UsersInRoles with RoleId and UserId.

Now I want to give all users that do not have the RoleName "MyRoleName" the existing RoleName "RoleNameToBeGiven".

I can get all the UserIds without the property "MyRoleName" as follows:

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')

Now I want to add every UserId obtained in this query into aspnet_UsersInRoles with the RoleId belonging to RoleName "RoleNameToBeGiven". To obtain the RoleId of "RoleNameToBeGiven" I have the following query:

SELECT RoleId FROM dbo.aspnet_Roles
WHERE RoleName = 'RoleNameToBeGiven'

The question is: how do I combine this two queries and insert every UserId obtained in the first query into the aspnet_UsersInRoles" table with theRoleId` obtained in the second query?

Это было полезно?

Решение

Seems like I found a working solution with the help of 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; 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top