views:

168

answers:

2

Hi, I am running SQL Server 2005 (express). I am trying to use DATEFORMAT and CONVERT in my queries. I am running into problems, so I first wanted to ask if those functions can be used everywhere.

I already know they can be used in SELECT. But can they be used in WHERE as well?

For example:

SELECT * 
    FROM review AS R, section AS SC, class AS CL, inserted AS M, section AS SC2, class AS CL2 
    WHERE 
    R.sectionId=SC.sectionId AND SC.classId=CL.classId AND
    M.sectionId=SC2.sectionId AND SC2.classId=CL.classId AND
    CL.classYear=CL2.classYear AND CL.classQuarter=CL2.classQuarter AND
    M.meetingDay = DATEPART(weekday,R.reviewStart) AND
    (
     CONVERT(VARCHAR(8), R.reviewStart, 108) between CONVERT(VARCHAR(8), M.meetingStart, 108) and CONVERT(VARCHAR(8), M.meetingEnd, 108) OR
     CONVERT(VARCHAR(8), R.reviewEnd, 108) between CONVERT(VARCHAR(8), M.meetingStart, 108) and CONVERT(VARCHAR(8), M.meetingEnd, 108) OR
     CONVERT(VARCHAR(8), M.meetingStart, 108) between CONVERT(VARCHAR(8), R.reviewStart, 108) and CONVERT(VARCHAR(8), R.reviewEnd, 108) OR
     CONVERT(VARCHAR(8), M.meetingEnd, 108) between CONVERT(VARCHAR(8), R.reviewStart, 108) and CONVERT(VARCHAR(8), R.reviewEnd, 108)
    )

See the use in M.meetingDay = DATEPART ... As well as in all parts of the BETWEEN thing.

Is that legal?

Thanks

+1  A: 

Yes it is legal

You don't say what the problem you are experiencing is so I can't offer much guidance but I would be inclined to take a look at the length of your varchar string. A datetime string requires more than 8 characters; are you truncating part of the string by the use of varchar(8).

Karl
Format 108 is of the form hh:mi:ss, which is 8 characters.
Michael Petrotta
Yes I am trying to get only the hh:mm:ss part of the datetime in that case.I guess I'll post my full SQL, and my error message then.Should I create a new question?
nute
If the question contents is significantly different, then yes, a new question is appropriate.
Michael Petrotta
Will the "between" work even though it's been converted to varchar?
nute
Yeah, I was wondering about the between; I suspect that what might be happening is you're getting an ASCII comparison of the time-value strings rather than a time-value comparison. Consider using DATAPART and/or a cast to a numeric value.
Karl
A: 

Maybe is a bit off topic but you should investigate moving to SQL 2008 Express and use the new datetime types introduced with 2008, since there is the new time type that stores exactly the time of the day (w/o the date part).

Remus Rusanu
I'm using a remote server, so no choice on the server ...But it's OK, it's for a school project and it's almost over.It all works fine now, thanks
nute