我有一个表,一些部门用户标记为
User | Department
user1 | IT,HR,House Keeping
user2 | HR,House Keeping
user3 | IT,Finance,HR,Maintainance
user4 | Finance,HR,House Keeping
user5 | IT,HR,Finance
我创建了一个以参数varchar(max)作为过滤器的SP(如果在C#代码中我动态合并)
在sp i中创建所选过滤器的临时表,例如;如果用户选择IT&金融与财务HR
我将字符串合并为IT ## Finance ## HR(在C#中)&使用此参数调用sp
SP中的我将临时表格作为
FilterValue
IT
Finance
HR
现在问题是如何获取包含所有部门的记录 (与临时表中的所有值相关联的用户)获取
User | Department
user3 | IT,Finance,HR,Maintainance
user5 | IT,HR,Finance
as optput
请建议一种优化的方法来实现此过滤
答案 0 :(得分:1)
这种设计太可怕了 - 你应该真正改变它,使用真正的关系设计和依赖表。
也就是说,如果你无法改变设计,你可以解决XML问题,它可能会给你带来好的表现。
尝试这样的事情(根据需要将'@test'替换为你的表名......)。你甚至不需要创建临时表 - 这会将你逗号分隔的字符串变成XML,然后你可以直接使用XQuery:
DECLARE @test TABLE (usr int, department varchar(1000))
insert into @test (usr, department)
values (1, 'IT,HR,House Keeping')
insert into @test (usr, department)
values (2, 'HR,House Keeping')
insert into @test (usr, department)
values (3, 'IT,Finance,HR,Maintainance')
insert into @test (usr, department)
values (4, 'Finance,HR,House Keeping')
insert into @test (usr, department)
values (5, 'IT,HR,Finance')
;WITH departments (usr, department, depts)
AS
(
SELECT usr, department, CAST(NULLIF('<department><dept>' + REPLACE(department, ',', '</dept><dept>') + '</dept></department>', '<department><dept></dept></department>') AS xml)
FROM @test
)
SELECT departments.usr, departments.department
FROM departments
WHERE departments.depts.exist('/department/dept[text()[1] eq "IT"]') = 1
AND departments.depts.exist('/department/dept[text()[1] eq "HR"]') = 1
AND departments.depts.exist('/department/dept[text()[1] eq "Finance"]') = 1