Handling different conditions present in table parameter to work as “AND” instead of “OR”
-
04-06-2021 - |
Question
I have a page where user dynamically add search condition(s) to filter out records. I am sending those conditions to stored proc in a TVP. Now i need to write a query which applies those filters work as "AND" instead of "OR"
Consider an example of student table
ID Name Marks
----------- --------- -------
2 bab 65
4 bad 75
6 baf 85
I am getting conditions to Stored proc in TVP as (i am sending Ids for column and operator, but for clarity i used column name and operator in this example)
Column Operator Value
----------- --------- -------
Name Contains a
Marks >= 75
Now i need to use this TVP to filter out records from student table, in this example the last 2 rows of student table will be displayed to user.
Can anyone help me in writing a query for this, i tried making cross join between student table and TVP, but query is ORing instead of ANDing the conditions in TVP
Sample query:
DECLARE @tmpCond TABLE
(
ColumnId SMALLINT,
OperatorId SMALLINT,
Value VARCHAR(10)
)
INSERT INTO @tmpCond
( ColumnId ,
OperatorId ,
Value
)
VALUES ( 1,1,'a')
,(2,2,'75')
SELECT * FROM dbo.Student A
CROSS JOIN @tmpCond B
WHERE
(B.ColumnId = 1 AND B.OperatorId = 1 AND A.NAME LIKE '%'+B.Value+'%')
OR
(B.ColumnId = 2 AND B.OperatorId = 2 AND A.Marks >= B.Value)
Solution
You need to do the following:
- Create the preliminary query as a string, missing the where parameters:
query = 'select * from student where xxx order by name, marks'
. We'll replacexxx
with proper contents. - Create the a variable for the query part
where_part = ''
- Use a cursor to iterate through every row in TVP
- For every
column, operator, value
in TVP, build up a string likename + operator + value + ' and '
and append it towhere_part
. - After having processed all rows from TVP, remove the last
' and '
, in this sense: 'condition and condition and conditionand'. - Replace
'xxx'
inquery
withwhere_part
- Run
exec(@query)
(tsql, other DBs have different syntax). See also this article and google for "dynamic sql in stored procedures ".