Update list of rows from subquery

Posted on 2011-05-09
Last Modified: 2012-05-11
I'll start by explaining my tables:

aspnet_Users:             UserID, UserName . . .
aspnet_Roles:              RoleID, RoleName . . .
aspnet_UsersInRoles:  UserID, RoleID

I want a query that assigns a role to all users that currently do not have a role.

One of my attempts:

INSERT INTO aspnet_UsersInRoles 
(SELECT UserId FROM aspnet_Users WHERE UserId NOT IN (SELECT UserId FROM aspnet_UsersInRoles))

Open in new window

Question by:echobridge
    LVL 1

    Author Comment

    Please note that if a user does not have a role, they will not be in the UsersInRoles table.
    LVL 40

    Accepted Solution

    try this.
    INSERT INTO aspnet_UsersInRoles(UserID, RoleID)
    SELECT UserId,'DEA47E12-1BFA-45C0-B994-F35025833922' 
      FROM aspnet_Users t1
     WHERE NOT EXISTS (SELECT 1 FROM aspnet_UsersInRoles t2 WHERE t1.UserId = t2.UserId)

    Open in new window

    LVL 142

    Expert Comment

    by:Guy Hengel [angelIII / a3]
    insert or update?

    if it's update, please read this article:
    LVL 1

    Author Closing Comment

    WOO! Worked perfect!!

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Join & Write a Comment

    As they say in love and is true in SQL: you can sum some Data some of the time, but you can't always aggregate all Data all the time! Introduction: By the end of this Article it is my intention to bring the meaning and value of the above quote to…
    If you find yourself in this situation “I have used SELECT DISTINCT but I’m getting duplicates” then I'm sorry to say you are using the wrong SQL technique as it only does one thing which is: produces whole rows that are unique. If the results you a…
    Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    19 Experts available now in Live!

    Get 1:1 Help Now