Click here to Skip to main content
15,903,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI all

i have one table where on column stores comma separated values

roleid
1,2,4,6,7
3,4,6,7,8
2,3,4,5,6
1,2,3,5,6,7


this are the role id which assigns to the user. now i want to get user by role.

if admin select role id 3 then it should return all the users which are assign to role id 3. i do not want to use cursor for this as it will affect the performance of the query. i don't have any other ideas. can some one please help me ?
Posted
Comments
[no name] 5-Jun-14 9:41am    
how about using CONTAINS ?
Vi(ky 5-Jun-14 10:23am    
Is there any table that map role to user?

Assuming you are looking for userids that have roleid=3, try CHARINDEX like this:
select userid from table1 where CHARINDEX('3', roleid ) > 0

However, it is bad practice to have multiple values in a single field, that is against 1NF principle. Instead, you should have a table with userid and roleid fields (both composite primary key) like this:
userid       roleid
  1             1
  1             2
  1             4
  1             6
  1             7
  2             3
  2             4
...
 
Share this answer
 
v3
You can use the LIKE operator, see "SQL LIKE Operator" at w3schools.com[^].
 
Share this answer
 
Assuming your table structre is like below

UserId AssignedRoles
1 1,12,3,4,5,6
2 6,3,23,1,4
5 2,11,19,12,34


SQL
DECLARE @TABLE TABLE (UserId TINYINT, AssignedValues VARCHAR(500))
INSERT INTO @TABLE VALUES (1, '1,12,3,4,5,6')
,(2, '6,3,23,1,4' )
,(3, '2,11,19,12,34')

DECLARE @UserId INT = 3, @RoleId INT = 19


SELECT *
FROM @Table t
WHERE UserId = @UserId
AND @RoleId IN (SELECT Value
                FROM dbo.Split(AssignedValues, ',')
                )


Here dbo.Split is the normal split function. If you dont have it in your db it is a google search away.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900