Solved

How to place a condition in a filter criteria in t-sql?

Posted on 2016-11-21
12
70 Views
Last Modified: 2016-11-22
Hi Experts,

I'm building a dynamic sql string and looking for the following.

Lets say there are two fields a text field (varchar 1000) and a date field.

Now I would like to filter for a date range in the date field, lets say between '1/1/16' and '2/1/16' but that should only be in case the text field contains a certain wording something like '%My Wording%'.

However in case the text field does not contain that word then I would want to see the record regardless of the date.

What is the simplest way to compose that?
(simple I mean in terms of clearness in reading, but at the same time should not compromise performance)
0
Comment
Question by:bfuchs
  • 8
  • 3
12 Comments
 
LVL 33

Expert Comment

by:Norie
ID: 41896751
How are you currently building the SQL statement?
0
 
LVL 4

Author Comment

by:bfuchs
ID: 41896758
Hi,

I'm using Access VBA to build that, its an ADP project so needs to be t-sql syntax.

Here is some extract of code...
    If Nz(txtLetterRange, "") <> "" Then
        If InStr(txtLetterRange, "-") > 0 Then
            sStr = sStr & " And  EmpName like '[" & txtLetterRange & "]%'"
        Else
            sStr = sStr & " And  EmpName like '" & txtLetterRange & "%'"
        End If
    End If

Open in new window

Thanks,
Ben
0
 
LVL 28

Expert Comment

by:Pawan Kumar
ID: 41896805
Here is the sample code for you --

WHERE DateFields >=  
                  CASE WHEN Wording LIKE '%My Wording%' THEN '1/1/16' ELSE DateFields END
AND
        DateFields <=  
                  CASE WHEN Wording LIKE '%My Wording%' THEN '2/1/16' ELSE DateFields END

CREATE TABLE Wordings
(
	 ID INT
	,Wording VARCHAR(100)
	,DateFields DATETIME
)
GO

INSERT INTO Wordings VALUES
(1,'My Wording','1/1/16'),
(2,'My Wording','2/1/16'),
(3,'Pawan','1/1/16'),
(4,'Ramehs','5/1/16'),
(5,'My Wording','5/1/16')
GO

SELECT * FROM Wordings

WHERE DateFields >=  
			CASE WHEN Wording LIKE '%My Wording%' THEN '1/1/16' ELSE DateFields END
AND 
	  DateFields <=  
			CASE WHEN Wording LIKE '%My Wording%' THEN '2/1/16' ELSE DateFields END

Open in new window


Output 

Open in new window


Note - The code is filtering the records (5,'My Wording','5/1/16') since it date is outside our range.

ID          Wording                                                                                              DateFields
----------- ---------------------------------------------------------------------------------------------------- -----------------------
1           My Wording                                                                                           2016-01-01 00:00:00.000
2           My Wording                                                                                           2016-02-01 00:00:00.000
3           Pawan                                                                                                2016-01-01 00:00:00.000
4           Ramehs                                                                                               2016-05-01 00:00:00.000

(4 row(s) affected)

Open in new window


Hope it helps !!
0
The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

 
LVL 4

Author Comment

by:bfuchs
ID: 41896848
Hi Pawan,

Will test & let you know.

Thanks,
Ben
0
 
LVL 4

Author Comment

by:bfuchs
ID: 41896907
Hi,

The example you posted works for two particular dates, but I need it to work for a date range, something the follows

1- >= '1/1/16'

2- between '1/1/16' and '2/1/16'

tried modify your code but getting an error.

Thanks,
Ben
0
 
LVL 4

Author Comment

by:bfuchs
ID: 41896923
Hi Pawan,

Actually disregard my previous post, I see that do work for date range as well.

However I do have an issue with null values, meaning in your example if field wording is lets say 'pawan' and datefields is null it will not come up.

Let me know how to adjust that.

Thanks,
Ben
0
 
LVL 28

Accepted Solution

by:
Pawan Kumar earned 500 total points
ID: 41896928
Try this.

Option 1--

SELECT * FROM Wordings
WHERE ( DateFields >=  
			CASE WHEN Wording LIKE '%My Wording%' THEN '1/1/16' ELSE DateFields END OR DateFields IS NULL )
AND 
	  ( DateFields <=  
			CASE WHEN Wording LIKE '%My Wording%' THEN '2/1/16' ELSE DateFields END OR DateFields IS NULL )

Open in new window



Option 2


SELECT * FROM Wordings
WHERE 
	  ISNULL( DateFields , '' ) >=  CASE WHEN Wording LIKE '%My Wording%' THEN '1/1/16' ELSE ISNULL(DateFields ,'') END
AND 
	  ISNULL( DateFields, '') <=  CASE WHEN Wording LIKE '%My Wording%' THEN '2/1/16' ELSE ISNULL(DateFields ,'') END

Open in new window

0
 
LVL 4

Author Comment

by:bfuchs
ID: 41896934
OK, your second option seems to work, however will do additional testing tom & let you know.

Thanks,
Ben
0
 
LVL 28

Expert Comment

by:Pawan Kumar
ID: 41896938
Sure , I will wait for your +ve response. :)

Bye !!
0
 
LVL 4

Author Closing Comment

by:bfuchs
ID: 41898159
Hi Pawan,

This works great, Thank you!
0
 
LVL 4

Author Comment

by:bfuchs
ID: 41898177
BTW, is there a way to have the 'between '1/1/16' and '2/1/16' when using it in this case?

the reason for asking is that this would be easier for me to integrate into my app, as I have this syntax already for other cases.

Thanks,
Ben
0
 
LVL 4

Author Comment

by:bfuchs
ID: 41898232
Hi Pawan,

Sorry for letting you wait:)
I have another one for you..

https://www.experts-exchange.com/questions/28984854/How-to-place-a-condition-in-a-filter-criteria-in-t-sql-2.html

Thanks,
Ben
0

Featured Post

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question