简体   繁体   中英

Many to Many relation query with dynamic where clause

My tables are :

Table Emp:-
EmpId, EmpName

Table EmpDeptTrans:-
EmpDeptID, EmpID, DeptID

table Dept:-
DeptID, DeptName

Business logic is that one employee can work in multiple department and one department can have multiple employees, so basically its many to many relation.

i need help in forming the SQL query where i can put my conditions like:

(dept='Engineering' and dept='Account' ) And (dept ='Library' or dept ='HR')

my where condition is dynamic and can change based on requirement...

as i can understand the question. is that you have written the condition in you xml data. where the expression could be something like

(dept='Engineering' and dept='Account' ) And (dept ='Library' or dept ='HR')

so what all you need to do is.

Create a plan query which show the all employee and department relation. now add your complex filter condition as you desire. like below

declare @complex nvarchar(1000);
set @complex = "(dept='Engineering' and dept='Account' ) And (dept ='Library' or dept
 ='HR')"

execsql query+' '+ @complex;

sorry, need more input for best answer.

you can use IN for multiple department like..

select .... where emptrans.deptid in('101','102')

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