Solved

building a query from one table with multiple betweens and or ors

Posted on 2012-12-26
16
193 Views
Last Modified: 2012-12-27
Hello-

I have a very complex (well I think it is complex anyway) query I need written. I am running MSSQL 2005.

I am wishing to have a query tell me the tasks that need to be completed at a specific time.  These tasks are all unique and there are about 75 different tasks that should show up at various times of the week and or year and or time of day.

For example:  I have "clean baseboards" in the "tasksubject" field and "a more descriptive explanation" in the "taskbody" field.  This task should only be done between the hours of 16:00 and 23:59 hours in the month of December only and only on a Friday.

I plan to run this query 3 times a day to produce a result.  I just need the query in a view format and I can do the rest.  The query will be ran @ 00:05 @ 8:05 and @ 16:05 every day.

The other data for the time field is 17:00

The data in the month fields s

Here is the table with the following columns (I have all data types set to nvarchar(MAX) I can easily change that if needed): I also put the common data that would be in each of the fields)

tasksubject (text and always different)
taskbody (text and always different)
dayofweek (Only a MON, TUE, WED, THU, FRI, SAT, SUN - but it could have more than one not just one)
month (Only a 1,2,3,4,5,6,7,8,9,10,11,12 - it could be just one or it could have more than one
time (always in military time and just XX:XX)

So with the example I have above it has the following data in each column:

tasksubject:  clean baseboards
taskbody: a more descirptive explanation
dayofweek: FRI
month: 12
time: 17:00

Another example:

tasksubject: clean toaster
taskbody: clean out the toaster in the breakroom
dayofweek: MON, THU, SAT
month: 1,2,3,4,5,6,7,8,9,10,11,12
time: 11:00

This above example would create a result on Monday, Tuesday, and Saturday every month at 11 AM.  

I will be running this query like I mentioned above 3 times a day so I think a between statement would be used for the date time.


If you have questions please let me know.  I am sure this is a lot of work and I really appreciate it.

Ben
0
Comment
Question by:binaryman101
  • 10
  • 3
  • 3
16 Comments
 
LVL 12

Accepted Solution

by:
Jared_S earned 500 total points
Comment Utility
I think you're going to have to use dynamic sql if you want to use your existing data structure - and since that's the case, I would build this as a stored procedure rather than a view.

This is a stored procedure that will find tasks that match the month, day of the week, and have a time that is less than 8 hours away from the run time of the procedure.

CREATE PROCEDURE sp_myProcedure AS

EXEC ('select * from mytable
where [month] = datepart(month,getdate())
and convert(datetime,[time]) between
convert(datetime,left(convert(varchar,getdate(),8),5)) and
convert(datetime,left(convert(varchar,dateadd(hh,8,getdate()),8),5))
and dayofweek like ' +'''%'+ substring(datename(weekday,getdate()),0,4) +'%''')

You'll want to replace the bold sections with whatever is appropriate.
0
 

Author Comment

by:binaryman101
Comment Utility
Give me a couple of hours to review this.  I believe I understand what you are asking.  I have only done a stored procedure a couple of times.  Ill let you know how it works.  Thank you so much!
0
 

Author Comment

by:binaryman101
Comment Utility
I get the following error:  

Msg 102, Level 15, State 1, Procedure frontdeskProcedure, Line 8
Incorrect syntax near 'substring'.
0
 
LVL 12

Expert Comment

by:Jared_S
Comment Utility
Sorry... use this for the procedure code instead (execute it first to make sure I'm not missing anything else).

--CREATE PROCEDURE sp_myProcedure AS

declare @day as varchar(5)
set @day = (select substring(datename(weekday,getdate()),0,4))

declare @sql as varchar(500)
set @sql =
'select * from mytable
where [month] = datepart(month,getdate())
and convert(datetime,[time]) between
convert(datetime,left(convert(varchar,getdate(),8),5)) and
convert(datetime,left(convert(varchar,dateadd(hh,8,getdate()),8),5))
and dayofweek like ' +'''%'+ @day +'%'''

exec  (@sql)
0
 

Author Comment

by:binaryman101
Comment Utility
No error this time.  

However, no results were produced.  Here is what is what I have in my table right now:

Clean baseboards      This is instructions on how to clean baseboards      WED      12      16:00
Clean carpet              this is a test instruction                                              WED      12      17:00
Wash                        Windows      Task of cleaning a window                      THR      12      17:00


It should have two that produced and nothing did?
0
 
LVL 1

Expert Comment

by:Dodsworth
Comment Utility
If you changed your dayofweek column to a number like you have with your months then this could easily be achieved using a view, I think.
0
 

Author Comment

by:binaryman101
Comment Utility
I changed it to this :  

Clean baseboards      This is instructions on how to clean baseboards      5      12      16:00
Clean carpet              this is a test instruction                                            4      12      17:00
Wash                        Windows      Task of cleaning a window                      6      12      17:00

Still zero results.
0
 

Author Comment

by:binaryman101
Comment Utility
How should it be written to make it a view instead?  I would prefer it as a view if possible.
0
Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 
LVL 1

Expert Comment

by:Dodsworth
Comment Utility
First let me know if you can change the structure of your table?

Is TaskSubject simply a shorted heading for TaskBody?

eg..

"tasksubject: clean toaster" will always be "taskbody: clean out the toaster in the breakroom"?


If this is the case then you may want to consider splitting your table into "Task" and "TaskFrequency"

This way you do not have to store multiple days and months in the same column and so can simply hit your data with a query.  You can also amend the times and days that each task needs to be carried out without having to resort to string manipulation on those dodgy multivalued columns.
0
 

Author Comment

by:binaryman101
Comment Utility
The table can be changed, however....

tasksubject is actually data that will be put into a subject line email.

taskbody is actually the body of the email.  

Once I get the query producing the values I want then I will create a cursor to generate emails for me to a ticket system we have.  

I don't need help making the cursor as I do those all the time I just can't figure out how to make this query work.  

We are taking multiple checklists staff has to follow and putting this all into a ticket system that will assign tasks to them on down days rather than them having to go work off a checklist.  

Thanks

Ben
0
 
LVL 1

Expert Comment

by:Dodsworth
Comment Utility
so the task subject is the Id that you need to return for a given call to the query
0
 

Author Comment

by:binaryman101
Comment Utility
I need to return both the tasksubject and taskbody for the results.
0
 

Author Comment

by:binaryman101
Comment Utility
If it helps I can store items in the time field instead of 11:00 it can be 11.  Looking for suggestions.
0
 
LVL 12

Expert Comment

by:Jared_S
Comment Utility
For the suggestion I posted:
You should be getting some results. There are probably fields that matching in the WHERE clause because of how they are (or are not) being converted. You can try taking out all of the WHERE criteria, and then adding them back in one by one to see which field conversion is the problem.  

A view can't be used because of the variable declaration.

A variable MUST be declared because of the method of storing the days of the week .

Because the day of the week column is a string that contains more than one day of the week value ('Wed, Thu, Fri' or '3, 4, 5')

the WHERE statement needs to state that    
dayofweek like '%Thu%'      -- or with numbers
dayofweek like '%4%'  

the only way to build the string like that is  with dynamic sql.

If you change the way you store that field's data it will let you get rid of the dynamic sql and write the query as a view.
0
 

Author Comment

by:binaryman101
Comment Utility
Ill try this suggestion tomorrow.  Thank you.
0
 

Author Closing Comment

by:binaryman101
Comment Utility
Thank you.  I figured out what I did wrong.  I had THR in the dayofweek instead of Thursday.  Thank you

Ben
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Recently, when I was asked to create a new SQL 2005 cluster, Microsoft released a new service pack for MS SQL 2005 what is Service Pack 3. When I finished the installation of MS SQL 2005 I found myself troubled why the installation of SP3 failed …
Data architecture is an important aspect in Software as a Service (SaaS) delivery model. This article is a study on the database of a single-tenant application that could be extended to support multiple tenants. The application is web-based develope…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

772 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

12 Experts available now in Live!

Get 1:1 Help Now