I have a Conditions table that looks like this :
Conditions
- ConditionID
- MappingID
- VariableID
- CompareToVariableID
- ConditionOperator ( can be == or <> )
- ConjunctionOperator ( can be && or || )
- ConjunctionOrder
Now I have a SP that I want to implement these conditions on depending on MappingID.
If a MappingID is selected, all mapped conditions should be checked before anything happens in my SP.
SELECT *
FROM Conditions
WHERE MappingID = @MappingID
ORDER BY ConjunctionOrder
For example if a certain MappingID had three rows in the Conditions table then :
IF VARIABLEID CONDITIONOPERATOR COMPARETOVARIABLEID CONJUNCTIONOPERATOR --row1
VARIABLEID CONDITIONOPERATOR COMPARETOVARIABLEID CONJUNCTIONOPERATOR --row2
VARIABLEID CONDITIONOPERATOR COMPARETOVARIABLEID --row3 (ignore ConjunctionOperator for last row)
BEGIN
--my code goes here
END
ELSE
BEGIN
--my code here
END
I would like to know how I can implement the IF statement.
One way of doing it is like this (these are the steps in your stored procedure)
Conditonstable and produce a special booolean expression out of it. You can do it by using a cursor over yourSELECTquery from your post. You should convert your variable IDs so that they won’t mix with the variable values (you’ll see later what I mean). Let’s suppose your query returned:Your expression (kept in a local SP variable) should be:
In other words you add
SELECT 1 WHEREat the beginning and relpace condition operator==with=and conjunction operator&&with ‘AND’, and||with ‘OR’Now you do a cursor query over your
Variablestable. In each loop you replace the names of the variables with its values (i.e. #A# is replaced with A value). At the end your expression should look like ‘SELECT 1 WHERE 1=2 AND 3<>3’.You use sp_executesql to execute your dynamically created query. You can put the output in an OUTPUT parameter and check it in your
IFstatment in your SP.