Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Split field values

Author  Topic 

olta
Starting Member

1 Post

Posted - 2009-06-02 : 05:58:20
Hello,
I have two tables : Roles and Users. In the Roles table I have inserted some roles. In user table I have inserted new Users and they respective roles in one field. All the roles in the field are divided by (,) in the users table.

I want to select a user and see his roles. For example :

username roles
john 1,2,6,7

The numbers in the roles field in users table are the respective id_roles in the roles table. I want to access their names and display something like this
username roles
john save
edit
delete
.....

Any Idea on how this is performed ???
Thankyou in advance

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2009-06-02 : 06:01:33
cross apply to CSVTable or fnParseList
then inner join to roles table

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=25830&SearchTerms=CSVTable
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=76033


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

bklr
Master Smack Fu Yak Hacker

1693 Posts

Posted - 2009-06-02 : 08:34:06
try like this too..
declare @str table(username varchar(32),roles varchar(128))
insert into @str select 'john','1,2,6,7'


select username, rolename
from (
SELECT username,
replace(SUBSTRING(s.roles,charindex(',',s.roles,v.number),abs(charindex(',',s.roles,charindex(',',s.roles,v.number)+1)-charindex(',',s.roles,v.number))),',','')as roleid
FROM @str AS s
INNER JOIN master..spt_values AS v ON v.Type = 'P'
and v.number > 0
and v.number <= len(s.roles)
WHERE substring(',' + s.roles, v.number, 1) = ',')s

inner join roles r on s.roleid = r.respective id
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-06-02 : 08:46:54
Also you should read about Normalisation

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -