I'm trying to build dynamic sql from a string passed by a calling
application. Let's assume for this discussion that the user can pass a
string of letters with these logical operators ("and", "or", and "and
not") seperating them. Each letter can be rebuilt into a sub query
that will search for people in a table by their middle initial. For
example,
X and Y
(select SSN from tblPerson where MiddleInitial = 'X') UNION
(select SSN from tblPerson where MiddleInitial = 'Y')
This seems pretty easy with the and operator (UNION) but how can I do
"or" and "and not"? I remember from a SQL class I had 10 years ago
that there was an INTERSECTION operator but it appears that T-SQL
doesn't support it. The closest option is EXIST and NOT EXIST but
these can not be simply inserted between two sub queries (I think),
they require the user of a where clause. It would obviously work in
the example above but in the more complecated example below it wouldn't
be an easy replacement of the operators and sub queries.
X and (Y or J) and not L
So, the bottom line is that I have no problem replacing the letters
with the appropriate sub query but I'm looking for a way to replace the
logical operator with SQL syntax that will mimic the logical operator.
I hope this makes sense. : )
Will Wirtz
application. Let's assume for this discussion that the user can pass a
string of letters with these logical operators ("and", "or", and "and
not") seperating them. Each letter can be rebuilt into a sub query
that will search for people in a table by their middle initial. For
example,
X and Y
(select SSN from tblPerson where MiddleInitial = 'X') UNION
(select SSN from tblPerson where MiddleInitial = 'Y')
This seems pretty easy with the and operator (UNION) but how can I do
"or" and "and not"? I remember from a SQL class I had 10 years ago
that there was an INTERSECTION operator but it appears that T-SQL
doesn't support it. The closest option is EXIST and NOT EXIST but
these can not be simply inserted between two sub queries (I think),
they require the user of a where clause. It would obviously work in
the example above but in the more complecated example below it wouldn't
be an easy replacement of the operators and sub queries.
X and (Y or J) and not L
So, the bottom line is that I have no problem replacing the letters
with the appropriate sub query but I'm looking for a way to replace the
logical operator with SQL syntax that will mimic the logical operator.
I hope this makes sense. : )
Will Wirtz
Comment