2012年2月9日星期四

Basic SQL Query (Select Records Added Today)

Hi,
I feel stupid for posting this question but I cannot find out how to create an SQL statement to return records that have been added today.
My database table has a field called calldate which hold the date and time of the record added to the database i.e. "02/08/2005 16:55:41".
Please can someone let me know how I can search to find all records added today. I thought it would be something like it, but I assume I need to format the calldate so it's just 02/08/2005.
Select *
From Table
Where CallDate = GetDate()
Thanks
BrettYou may try something as:
SELECT
*
FROM
Table
WHERE
(
(DAY(CallDate) = DAY(GETDATE())
AND
(YEAR(CallDate) = YEAR(GETDATE())
)
Hope this works for you
Regards|||

you may want to use the month too , as the day number and year may match but not the month:

SELECT
*
FROM
Table
WHERE
(
(DAY(CallDate) = DAY(GETDATE())
AND
(MONTH(CallDate) = MONTH(GETDATE())
AND
(YEAR(CallDate) = YEAR(GETDATE())
)

|||I missed that, sorry.
Regards
|||I tried the code but it does not work, any other ideas?|||What do you mean it didn't work? the code is very simple and clear, tell us what the main problem is with this code.
regards
|||The error I receive is :-
Incorrect syntax near ')'.
Any idea's?
Thanks
Brett|||Problem now resolved
Select * from tbl
WHERE
(
DAY(CallDate) = DAY(GETDATE())
AND
MONTH(CallDate) = MONTH(GETDATE())
AND
YEAR(CallDate) = YEAR(GETDATE())
)
Thanks for your help,
Brett|||In fact you are right, I just noticed that.
Regards
|||I'd simplify it by using the DATEDIFF function:
SELECT * FROM tbl WHERE DATEDIFF(d,CallDate,GETDATE()) = 0
But for better performance, this would be preferable:
DECLARE @.startDate datetime, @.endDate datetime
SELECT @.startDate = CONVERT(char(8), GETDATE(),112), @.endDate = CONVERT(char(8), DATEADD(d,1,GETDATE()),112)
SELECT * FROM tbl WHERE CallDate >= @.startDate AND CallDate < @.endDate

The second option would perform better because a function is notperformed on each column of the table. Note that I am setting@.startDate equal to midnight of the current date (this is the defaultif a time is not specified), and I am setting @.endDate to midnight oftomorrow.

没有评论:

发表评论