Solved

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

Posted on 2016-11-21
12
31 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
Comment Utility
How are you currently building the SQL statement?
0
 
LVL 3

Author Comment

by:bfuchs
Comment Utility
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 17

Expert Comment

by:Pawan Kumar Khowal
Comment Utility
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
 
LVL 3

Author Comment

by:bfuchs
Comment Utility
Hi Pawan,

Will test & let you know.

Thanks,
Ben
0
 
LVL 3

Author Comment

by:bfuchs
Comment Utility
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 3

Author Comment

by:bfuchs
Comment Utility
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 17

Accepted Solution

by:
Pawan Kumar Khowal earned 500 total points
Comment Utility
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 3

Author Comment

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

Thanks,
Ben
0
 
LVL 17

Expert Comment

by:Pawan Kumar Khowal
Comment Utility
Sure , I will wait for your +ve response. :)

Bye !!
0
 
LVL 3

Author Closing Comment

by:bfuchs
Comment Utility
Hi Pawan,

This works great, Thank you!
0
 
LVL 3

Author Comment

by:bfuchs
Comment Utility
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 3

Author Comment

by:bfuchs
Comment Utility
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Basics of query design. Shows you how to construct a simple query by adding tables, perform joins, defining output columns, perform sorting, and apply criteria.

744 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now