Handling different conditions present in table parameter to work as “AND” instead of “OR”

StackOverflow https://stackoverflow.com/questions/10379001

  •  04-06-2021
  •  | 
  •  

Domanda

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)
È stato utile?

Soluzione

You need to do the following:

  1. Create the preliminary query as a string, missing the where parameters: query = 'select * from student where xxx order by name, marks'. We'll replace xxx with proper contents.
  2. Create the a variable for the query part where_part = ''
  3. Use a cursor to iterate through every row in TVP
  4. For every column, operator, value in TVP, build up a string like name + operator + value + ' and ' and append it to where_part.
  5. After having processed all rows from TVP, remove the last ' and ', in this sense: 'condition and condition and condition and '.
  6. Replace 'xxx' in query with where_part
  7. Run exec(@query) (tsql, other DBs have different syntax). See also this article and google for "dynamic sql in stored procedures ".
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top