You basically need to check if there is a role that has the exact number of distinct permissions as you are checking for.
I have checked this stored procedure on SQL Server 2005 and it returns only those role ids that have an exact match of permission ids to those in the passed in list of comma separated permission ids -
CREATE PROC get_roles_for_permissions (@list nvarchar(max)) -- @list is a comma separated list of your permission ids
AS
SET NOCOUNT ON
BEGIN
DECLARE @index INT, @start_index INT, @id INT
DECLARE @permission_ids TABLE (id INT)
SELECT @index = 1
SELECT @start_index = 1
WHILE @index <= DATALENGTH(@list)
BEGIN
IF SUBSTRING(@list,@index,1) = ','
BEGIN
SELECT @id = CAST(SUBSTRING(@list, @start_index, @index - @start_index ) AS INT)
INSERT INTO @permission_ids ([id]) VALUES (@id)
SELECT @start_index = @index + 1
END
SELECT @index = @index + 1
END
SELECT @id = CAST(SUBSTRING(@list, @start_index, @index - @start_index ) AS INT)
INSERT INTO @permission_ids ([id]) VALUES (@id)
SELECT
r.roleid
FROM
role r
INNER JOIN
role_permission rp
ON r.roleid = rp.roleid
INNER JOIN
@permission_ids ids
ON
rp.permissionid = ids.id
GROUP BY r.roleid
HAVING(SELECT COUNT(*)
FROM role_permission
WHERE roleid = r.roleid) = (SELECT COUNT(*) FROM @permission_ids)
END
Example Data
CREATE TABLE [dbo].[role](
[roleid] [int] IDENTITY(1,1) NOT NULL,
[name] [nvarchar](50)
)
CREATE TABLE [dbo].[permission](
[permissionid] [int] IDENTITY(1,1) NOT NULL,
[name] [nvarchar](50)
)
CREATE TABLE [dbo].[role_permission](
[roleid] [int],
[permissionid] [int]
)
INSERT INTO role(name) VALUES ('Role1')
INSERT INTO role(name) VALUES ('Role2')
INSERT INTO role(name) VALUES ('Role3')
INSERT INTO role(name) VALUES ('Role4')
INSERT INTO permission(name) VALUES ('Permission1')
INSERT INTO permission(name) VALUES ('Permission2')
INSERT INTO permission(name) VALUES ('Permission3')
INSERT INTO permission(name) VALUES ('Permission4')
INSERT INTO role_permission(roleid, permissionid) VALUES (1, 1)
INSERT INTO role_permission(roleid, permissionid) VALUES (1, 2)
INSERT INTO role_permission(roleid, permissionid) VALUES (1, 3)
INSERT INTO role_permission(roleid, permissionid) VALUES (1, 4)
INSERT INTO role_permission(roleid, permissionid) VALUES (2, 2)
INSERT INTO role_permission(roleid, permissionid) VALUES (2, 3)
INSERT INTO role_permission(roleid, permissionid) VALUES (2, 4)
INSERT INTO role_permission(roleid, permissionid) VALUES (3, 3)
INSERT INTO role_permission(roleid, permissionid) VALUES (3, 4)
INSERT INTO role_permission(roleid, permissionid) VALUES (4, 4)
EXEC get_roles_for_permissions '3,4' -- RETURNS roleid 3