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)
You need to do the following:
query = 'select * from student where xxx order by name, marks'
. We'll replace xxx
with proper contents.where_part = ''
column, operator, value
in TVP, build up a string like name + operator + value + ' and '
and append it to where_part
.' and '
, in this sense: 'condition and condition and condition'xxx'
in query
with where_part
exec(@query)
(tsql, other DBs have different syntax). See also this article and google for "dynamic sql in stored procedures ".