Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2012-12-26
16
Medium Priority
?
218 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 3
  • 3
16 Comments
 
LVL 12

Accepted Solution

by:
Jared_S earned 2000 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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

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

by Mark Wills PIVOT is a great facility and solves many an EAV (Entity - Attribute - Value) type transformation where we need the information held as data within a column to become columns in their own right. Now, in some cases that is relatively…
I am showing a way to read/import the excel data in table using SQL server 2005... Suppose there is an Excel file "Book1" at location "C:\temp" with column "First Name" and "Last Name". Now to import this Excel data into the table, we will use…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

610 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