OPSL OPSL - 4 months ago 6x
SQL Question

SQL Server Select With Loop on second table

I am struggling with some SQL logic and wondered if you can help?

I need to get a list of ID's from table "Roles" where emailEnabled is true, I then need to use these IDs against the table "Users" on the roleid column to grab their email addresses and return these as a comma separated list.

I know we need to use a loop in here but it's not my strong point.

Let me know if you need any further info.


I would not recommend generating a comma seperated list in SQL. Grab the data you need record-wise and handle the rest in your program logic.

You can get the data you need like this

select users.email
from users
join roles on roles.id = users.roleid
where roles.emailEnabled = 1