2

lets say I have 3 tables in my SQL database:

AspNetUserRoles - hold records that links user with role AspNetUsers - holds users AspNetRoles - holds roles

I wanted to update role assigned to user whose email is: some@email.com

I created this query and it works:

-- Update tester account role
Update  AspNetUserRoles
Set RoleId = 4
From AspNetUsers as b Inner Join AspNetUserRoles as a
    On a.UserId = b.Id Where b.Email = 'some@email.com'

Now, how to edit this query, instead of supplying RoleId (in this case 4), retrieve specific role ID from its table by specifying its name? AspNetRoles table has field 'name', I tried with another inner join but failed. Any help would be appreciated, thank you.

Joe Taras
  • 15,166
  • 7
  • 42
  • 55
Matthewek
  • 1,519
  • 2
  • 22
  • 42

4 Answers4

2

In your UPDATE query I've removed the JOIN because you have this information in your mail table.

So I've add the subquery to update your RoleId

Try this:

UPDATE AspNetUserRoles
SET RoleId = (SELECT c.id FROM AspNetRoles c WHERE c.name = 'MyRoleName')
FROM AspNetUsers as b 
WHERE b.Email = 'some@email.com'
AND AspNetUserRoles.UserId = b.Id
Joe Taras
  • 15,166
  • 7
  • 42
  • 55
1

You can write a query to fetch the id of the role depending of the name

SELECT r.id
FROM AspNetRoles r
WHERE r.name = 'YourRoleName'
LIMIT 1

And use this query as subquery in your main :

Update  AspNetUserRoles
Set RoleId = 
(
    SELECT r.id
    FROM AspNetRoles r
    WHERE r.name = 'YourRoleName'
    LIMIT 1
)
From AspNetUsers as b Inner Join AspNetUserRoles as a
    On a.UserId = b.Id Where b.Email = 'some@email.com'
Cid
  • 14,968
  • 4
  • 30
  • 45
1

You can use a JOIN like this:

update  aur
    set RoleId = 4
from AspNetUsers au join
     AspNetUserRoles  ur
     on aur.UserId = au.Id join
     AspNetRoles r
     on ur.RoleId = r.roleId
where au.Email = 'some@email.com' and
      r.Name = ?;

This seems strange, though. ApsNetUserRoles sounds like a junction table. I would expect you to add a role by inserting a role into this table.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Gordon : *"how to edit this query, instead of supplying RoleId (in this case 4), retrieve specific role ID from its table by specifying its name?"* – Cid Apr 08 '19 at 11:50
0

Try this:

  Update AspNetUserRoles
    Set AspNetUserRoles.RoleId = a.RoleId
    From AspNetUsers as b 
    Inner Join AspNetUserRoles as a
        On a.UserId = b.Id 
    Where b.Email = 'some@email.com'
      and  a.name = 'name'
Daniel Quinlan
  • 2,639
  • 1
  • 20
  • 23
Rima
  • 1,447
  • 1
  • 6
  • 12