Other folks are suggesting ways to detect dependent rows, but the problem with this is that there's a race condition: if your test finds no dependent rows, and you try to delete the group, there might be another client application that adds a dependent row in the brief moment between your two queries. So your information that the group is unused is potentially outdated as soon as you get it.
The better approach is to try to delete the group, and handle any errors that are raised.
This is also better for performance, because you don't have to run any SELECT
query to check if the dependent rows exist.
Re your comment and edited question: Okay, fair enough, it makes sense to use this information to give hints to the user (e.g. display a "delete group" button or else gray out the button).
In that case, you can use one of the suggestions from other folks, such as query the count of dependent rows in the Users
table. If you need information for multiple groups, I'd do one query, joining Groups
to Users
and then group by the group id.
SELECT g.groupid, COUNT(*) AS user_count
FROM dbo.Groups g JOIN dbo.Users u ON (g.groupid = u.groupid)
GROUP BY g.groupid;
That'd be better than running a separate SQL query for each group to get the count of users.
If you don't know how many tables may depend on Groups
, you should learn to use the INFORMATION_SCHEMA
system views to query for metadata. I don't think this is the case for you, so I won't go into detail.