Skip to content
Advertisement

T-SQL use an entire WHRE condition coming from a string in a field table

I want to perform a running where filtering for two table using T-SQL. I can only use T-SQL. I have several conditions for the same field, depending on the sensor type.

Instead of using something like this that works for only two conditions:

I would like to get the entire where condition from a table field (for instance, expression) in a reference table that includes as a string all the operators and a placeholder (%) for the comparing table field, saved like this:

"%>100 OR %<10"

Then, the expression could be evaluated like this:

Is it nearly possible? Can you guide me to it?

The reference table is a simple JSON file like this:

Advertisement

Answer

So you can create a dynamic query by using SP_EXECUTESQL (https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql?view=sql-server-ver15) and you can create the query you like. In your case, you need to evaluate multiple sensors at once, so I guess is not a one query thing, but an iteration within all sensor rather, so it would be something like this:

I tried to put as many comments on the code, so you’ll know what’s doing on each step.

Please update the queries with the ones you really have to get the expression from

UPDATE Added the Parenthesis to avoid conflics on the Where clause

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement