Is it possible to do something like what's happening here in the where statement @Age
param?
@AGE Varchar(8)
SELECT NAME FROM TABLE WHERE
(
If @AGE='man'
then (AGE = 'man' or AGE = 'boy')
else (AGE = 'man')
)
AND City IS NULL
Is it possible to do something like what's happening here in the where statement @Age
param?
@AGE Varchar(8)
SELECT NAME FROM TABLE WHERE
(
If @AGE='man'
then (AGE = 'man' or AGE = 'boy')
else (AGE = 'man')
)
AND City IS NULL
Yes, something like this:
SELECT NAME FROM TABLE WHERE
((@AGE='man'
AND (AGE = 'man' or AGE = 'boy'))
OR
(@AGE <> 'man'
AND (AGE = 'man')))
AND City IS NULL
Note the condition @AGE <> 'man'
may need to be tweaked depending on whether the @AGE variable can be null.
I answered a very similar question here.
This is a very common technique in a WHERE clause. If you want to apply some "IF" logic in the WHERE clause all you need to do is add the extra condition with an boolean AND to the section where it needs to be applied.
one way of doing this is with EXEC
and build the String command by If's
.
something like this :
declare @t nvarchar(max)
@AGE Varchar(8)
set @t=' SELECT NAME FROM TABLE WHERE '
If @AGE='man' set @t=@t+'(AGE = ''man'' or AGE = ''boy'')'
else set @t=@t+'(AGE = 'man')'
set @t=@t+' AND City IS NULL'
In conjunctive normal form ("a series of ANDs", less dependent on parans):
SELECT *
FROM TABLE
WHERE ( @AGE <> 'man' OR (AGE IN ('man', 'boy') ) )
AND ( @AGE = 'man' OR AGE = 'man' )
AND CITY IS NULL;
The idea here is to use the implication rewrite rule:
( IF x THEN y ) is equivalent to ( NOT ( x ) OR y )
Here's some test code:
WITH T
AS
(
SELECT *
FROM (
VALUES (1, 'man', NULL),
(2, 'boy', NULL),
(3, 'girl', NULL)
) AS T (NAME, AGE, CITY)
),
Params
AS
(
SELECT *
FROM (
VALUES ('man'),
('boy'),
('girl')
) AS T (p_AGE)
),
Results
AS
(
SELECT Params.*, T.*,
CASE WHEN ( ( p_AGE <> 'man' OR (AGE IN ('man', 'boy') ) ) AND ( p_AGE = 'man' OR AGE = 'man' ) ) THEN 'TRUE'
WHEN NOT ( ( p_AGE <> 'man' OR (AGE IN ('man', 'boy') ) ) AND ( p_AGE = 'man' OR AGE = 'man' ) ) THEN 'FALSE'
ELSE 'UNKNOWN'
END AS result_onedaywhen,
CASE WHEN ( AGE='man' OR (p_AGE='MAN' and AGE='boy') ) THEN 'TRUE'
WHEN NOT ( AGE='man' OR (p_AGE='MAN' and AGE='boy') ) THEN 'FALSE'
ELSE 'UNKNOWN'
END AS result_Damien_The_Unbeliever
FROM T, Params
)
SELECT *
FROM Results;
OR you could use decode functions