Solved

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

Posted on 2012-12-26
16
198 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
ID: 38722201
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
ID: 38722247
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
ID: 38722254
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
ID: 38722274
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
ID: 38722283
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
ID: 38722286
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
ID: 38722305
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
ID: 38722321
How should it be written to make it a view instead?  I would prefer it as a view if possible.
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 1

Expert Comment

by:Dodsworth
ID: 38722372
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
ID: 38722383
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
ID: 38722450
so the task subject is the Id that you need to return for a given call to the query
0
 

Author Comment

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

Author Comment

by:binaryman101
ID: 38722529
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
ID: 38722722
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
ID: 38722764
Ill try this suggestion tomorrow.  Thank you.
0
 

Author Closing Comment

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

Ben
0

Featured Post

Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to automate & schedule this Index optimization Script ? 10 76
create index to c1, c2 and c3 9 67
SQL Query 2 60
SQL query to summarize items per month 5 53
There are some very powerful Data Management Views (DMV's) introduced with SQL 2005. The two in particular that we are going to discuss are sys.dm_db_index_usage_stats and sys.dm_db_index_operational_stats.   Recently, I was involved in a discu…
So every once in a while at work I am asked to export data from one table and insert it into another on a different server.  I hate doing this.  There's so many different tables and data types.  Some column data needs quoted and some doesn't.  What …
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
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…

920 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

16 Experts available now in Live!

Get 1:1 Help Now