简体   繁体   中英

SQL Filter based on Multi-Row Security

We are currently using MS SQL Server 2005, but will soon be migrating to 2012 (or 2014). I am facing the following scenario.

data table (data)

id   | location | group  |  level
-----+----------+--------+---------
1    | loc1     |   A    |    1
2    | loc1     |   B    |    5
3    | loc1     |   A    |    9
4    | loc1     |   A    |   12
5    | loc2     |   A    |    1
6    | loc2     |   B    |    5

And this security table (security)

user | location | group | level from | level to
-----+----------+-------+------------+----------
u1   | loc1     |   A   |    1       |    5
u1   | loc1     |   A   |   10       |   15
u1   | loc2     |       |    4       |    9

The logic is that each value of one row in the security table is concatenated with "and" (if not null), each row with "or".

Currently I build the where clause dynamically in a stored proc as a simple string. This works fine with small number of security rows defined for a single user, but will take ages for 5000+ rows.

Example:

select id from data 
where location = 'loc1' and and group='A' and level>=1 and level <=5
location = 'loc1' and group='A' and level>=10 and level <=15
or location = 'loc2' and level>=4 and level <=9

-> id: 1, 4, 5, 6

I do not see any way to do this on SQL side in a smart way. Does anyone have a suggestion?

Select distinct id from data
Inner join security on data.location = security.location 
And data.group = security.group
And data.level between security.[level from] and [level to]

The distinct part is to prevent duplicated result give out from query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM