sql server - Check for multiple rows using joins -
i stuck while creating query this. below tables.
create table [dbo].[mst_conflict_roles] ( [crlm_id] [dbo].[its_bid] identity(1,1) not null, [crlm_roles] [varchar](10) not null, [crlm_description] [varchar](200) null, [crlm_added_by] [dbo].[its_userid] not null, [crlm_added_dt] [dbo].[its_datetime] not null, [crlm_last_updated_by] [dbo].[its_userid] null, [crlm_last_updated_dt] [dbo].[its_datetime] null, [crlm_data_del] [dbo].[its_tid] not null, constraint [pk_mst_conflict_roles] primary key clustered ([crlm_id] asc) ) on [primary] insert [mst_conflict_roles] values ('2,113', 'scheduler - auditor', 1, getdate(), 1, getdate(), 0), ('110,113','ae - scheduler',1,getdate(),1,getdate(),0), ('2,121','auditor - vendor cap user',1,getdate(),1,getdate(),0), ('8,9','am - ac',1,getdate(),1,getdate(),0) declare @userrole table(userid int, userrole int) insert @userrole values (1, 2),(1, 113),(1, 8),(1, 9),(1, 50),(2, 110),(2, 50),(3, 2),(3, 121) select * @userrole logic : if user role(userrole) match conflict table roles(crlm_roles) record must appear in output table.
output
userid crlm_id crlm_description 1 1 2,113 1 4 8,9 3 3 2,121 can tell me how can approach this?
the following query returns desired output:
with tmp ( crlm_id, crlm_roles, role_id, data ) ( select crlm_id , crlm_roles , convert(nvarchar, left(crlm_roles, charindex(',', crlm_roles + ',') - 1)) , stuff(crlm_roles, 1, charindex(',', crlm_roles + ','), '') [dbo].[mst_conflict_roles] union select crlm_id , crlm_roles , convert(nvarchar, left(data, charindex(',', data + ',') - 1)) , stuff(data, 1, charindex(',', data + ','), '') tmp data > '' ) select userid, crlm_id, crlm_roles crlm_description ( select crlm_id , crlm_roles , role_id , userrole.* , r = row_number() on ( partition userid, crlm_id order userid ) tmp join userrole on tmp.role_id = userrole.userrole ) x r = 2 option (maxrecursion 0); output:

Comments
Post a Comment