Hi I have the following type of query:
Select a,b from tab1 whre tab1.id in
(Select id from tab2 where x=1 and y=2 and z>getdate())
Now z is a datetime column in tab2 and it is nullable column.So I want the check z > getdate() only if it is not null. Checked Conditional WHERE clause in SQL Server but could not do it accurately.Basically I dont want the 'z' column check in the above query if it is null in tab2.
Thanks in advance.
Did you mean:
Select a,b from tab1 where tab1.id in
(Select id from tab2 where x=1 and y=2 and (z is null or (z is not null and z>getdate())))
I think you need a combination of AND and OR operators. When combining these you need to be aware of operator precedence. In my example I've used brackets to ensure that x, y AND z are checked together, with z then rechecked separately. The query returns any record where check block 1 OR 2 is true.
In my example I've used a JOIN but you can apply this same technique to your original sub query.
Example
SELECT
t1.a,
t1.b
FROM
Tab1 AS t1
INNER JOIN Tab2 AS t2 ON t1.Id = t2.Id
WHERE
(
-- Check block 1.
t2.x = 1
AND t2.y = 1
AND t2.z > GETDATE()
)
-- Check block 2.
OR z IS NULL
;
EDIT: I'm not entirely sure I understand the question. If you could provide some sample records and the expected output that would help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With