I have written following Query in SQL Server :
SELECT *
FROM AttendanceMaster
WHERE Date between '8/12/2012' AND '8/20/2012'
butt Query result returns '8/13/2012' AND '8/19/2012'
but it doesn't returns result for date 12/8/2012 and for date 8/20/2012
so what is the solution to get the data for above two date ?
Try with following query:
SELECT *
FROM AttendanceMaster
WHERE CAST(Date AS DATETIME)
BETWEEN DATEADD(DAY , -1 ,CAST('2012-08-12' AS DATETIME)) AND
DATEADD( DAY , 1 ,CAST('2012-08-20' AS DATETIME));
If you are using SQL Server 2008, you only need to do something like this:
SELECT *
FROM AttendanceMaster
WHERE CONVERT(DATE, [Date]) BETWEEN CAST('2012-08-12' AS DATE) AND CAST('2012-08-20' AS DATE)
EDIT: I am making 2 assumptions here.
1) That you have indeed confirmed that you have data in your AttendanceMaster table that has [Date] equal to 12th and/or 20th August 2012 - you dont want to look for something that is not even there in the first place ;)
2) That the [Date] column is most probably of DATETIME SQL Server type
its not TO but instead AND
select *
from AttendanceMaster
where Date between '8/12/2012' AND '8/20/2012'
try casting it to date
SELECT *
FROM AttendanceMaster
WHERE CAST([Date] AS DATE) BETWEEN CAST('2012-08-12' AS DATE) AND CAST('2012-08-20' AS DATE)
I would suggest you to use <, <=, >=, or > because they allow more flexibility than BETWEEN and you have the choice to including or exclude the endpoints.
So you can rewrite your query like this
SELECT *
FROM AttendanceMaster
WHERE Date > '8/12/2012 00:00:00' AND Date < '8/21/2012 00:00:00'
Plz note that in the above query the end date is 21st and not 20th.
Also remember that by default SQL Server will take any date like '8/20/2012' AS '8/20/2012 00:00:00' and therefore any datetime greater than this will not appear in result if you use BETWEEN or if you dont specify the exact time stamp.
Hope it helps.
If you give dates '2012-08-12' and '2012-08-20' then it returns the data between '2012-08-12 0:00 AM' and '2012-08-20 0:00 AM' So it does not return the valuesfrom the date '2012-08-12'. So you need to write the target date as '2012-08-21'
If you have the date '2012-08-20' in a variable for ex:
DECLARE #FromDate DATETIME
DECLARE #ToDate DATETIME
SET #FromDate = '2012-08-12'
SET #ToDate = '2012-08-20'
DECLARE #NextDate DATETIME
SET #NextDate=CAST(FLOOR(CAST(dateadd(day,1,#ToDate) AS FLOAT)) AS DATETIME)
/*This Returns the Next Day Date.*/
SELECT *
FROM AttendanceMaster
WHERE Date between #Date AND #NextDate
Or you can write as
DECLARE #FromDate DATETIME
DECLARE #ToDate DATETIME
SET #FromDate = '2012-08-12'
SET #ToDate = '2012-08-20'
SELECT *
FROM AttendanceMaster
WHERE Date between #Date AND CAST(FLOOR(CAST(dateadd(day,1,#ToDate) AS FLOAT)) AS DATETIME)
Related
I have a column "Uploaded" of type varchar(25). It has datetime values. Since the string stored in this column is not valid date(front-end is passing them. No control over there) it is kept as varchar(25). The strings stored in it are like:
2016:04:14 21:20:35
2016:04:14 21:20:35
2016:04:14 21:20:35
.
.
.
I need to compare these values in a search query
Select * from Table where [Uploaded] BETWEEN #StartDate AND #EndDate
#StartDate and #EndDate are date type variables. Obviously the above query won't work. So, I have 2 ways:
1. Write correct query that can compare the passed date type variables with the "Uploaded" column.
2. Update the [Uploaded] column values and re-store them as a valid datetime type.
How can that be achieved? Can someone help me writing either the correct search query or update all the records to convert them in valid datetime type?
If you got : between year, month and day in [Uploaded] field then use this:
SELECT *
FROM Table
WHERE CAST(REPLACE(LEFT([Uploaded],10),':','-') as date) BETWEEN #StartDate AND #EndDate
If datetime needed then:
SELECT *
FROM Table
WHERE CAST(REPLACE(LEFT([Uploaded],10),':','-') + RIGHT([Uploaded],9) as datetime) BETWEEN #StartDate AND #EndDate
This will give you accurate result.
select * from Table where cast(replace(left([Upholded],10),':','-')+right([Upholded],len([Upholded]-10) as datetime) between #StartDate AND #EndDate
you can cast the string data to a datetime value and then use datetime comparison
Select * from Table where CAST( [Uploaded] as Date) BETWEEN #StartDate AND #EndDate
make sure you use the right format for your datetime conversions and you should be golden.
here's some more info : https://msdn.microsoft.com/en-us/library/ms187819.aspx
I have the following query
DECLARE #StartDate DATETIME, #EndDate DATETIME
SET #StartDate = DATEADD(mm,-1, getdate())
select count(status) from [full]
where (date_reception> #StartDate and status = 'OPEN')
I need to get result of one month before now , for example we are in 2015-03-19 i need to get result from 2015-02-19 till now.
When i try query above i get as result (4412) and when i try (where date_reception >'2015-02-19') i get (5638)
If the time component of the date is not to be considered, try the following code. If it is, your current code seems accurate.
DECLARE #StartDate DATETIME, #EndDate DATETIME, #currentDate date
set #currentDate = GETDATE()
SET #StartDate = DATEADD(mm,-1, #currentDate))
select count(status) from [full]
where (date_reception> #StartDate and status = 'OPEN')
try
WHERE date_reception BETWEEN DATEADD(month, -1, GETDATE()) AND DATEADD(GETDATE())
I need some help.
I'm writing an webapplication in asp.net C#, I want to get the next birthday. I have.
1 field name birthdate, type DateTime. Ex: 1991-01-02 00:0000:0000 (yyyy-MM-dd). I want to show people have next birthday in repeater.
select * from tblBirthday where birthdate between 2015-01-01 and datenow
But now all I get in code behind with datetime.now is string type, birthdate is datetime type.
How I can get datetime.now with datetime type.
What is exactly your datenow is? Try to use the stored procedure, and make the date a parameter with datetime sql type, so it will work for a BETWEEN constructure, or use the built-in GETDATE() function on sql server side, like this:
select * from tblBirthday where birthdate between 2015-01-01 and GETDATE()
Make sure that in c#, you are passing DateTime.Now and not DateTime.Now.ToString()
or you can do your formatting of datetime "dd-MM-yy" and then cast it to proper datetime object like below...
DateTime datetimenow = DateTime.Parse(DateTime.Now.ToString("dd-MM-yy"));
use Sql CAST AND CONVERT
Syntax for CAST: CAST ( expression AS data_type [ ( length ) ] )
Syntax for CONVERT: CONVERT ( data_type [ ( length ) ] , expression [
, style ] )
like.
select * from tblBirthday where Cast(birthdate as date) between
cast('01/01/2015' as date) and cast(getdate() as date)
--where getdate() is the sql function to get current datetime.
CREATE procedure St_Proc_GetUserReportforCurrentDayTask
#userID int
as
Begin
set NoCount on;
DECLARE #TODAY DATE
SET #TODAY = CONVERT(VARCHAR(10), GETDATE(), 111)
select CONVERT(VARCHAR,production.CalendarDate,101) + RIGHT (CONVERT(VARCHAR,production.CalendarDate , 100 ) ,7) as Date,
RegionAndProjectInfo.RegionProjectName as Region ,
County.CountyName as County,
WorkType.WorkTypeName as WorkType,
Task.TaskName as Task,
Production.VolumeProcessed as 'Volumes Processed',
Production.TimeSpent as 'Duration'
from Production
inner join RegionAndProjectInfo
on
RegionAndProjectInfo.RegionProjectID=Production.RegionProjectID
inner join County
on
County.CountyID=Production.CountyID
inner join WorkType
on
WorkType.WorkTypeID=Production.WorkTypeID
inner join Task
on
Task.TaskID=Production.TaskID
where Production.UserID=#userID and CalendarDate >= #TODAY
End
From the above Stored Procedure i am filling a Dataset.After that i am binding this Dataset to a grid view.
In the dataset ,the Column Duration contains Data in HH:MM Format(example-01:00,12:45,02:59 etc).Is there a way that i can get the total of Duration in HH:MM format from the dataset itself.I dont want to query again from the Database to get the Sum of the Duration.
If you're using at least SQL-Server 2008, you should use Time datatype to represent a .NET TimeSpan.
To get it to work with a varchar-column, i would use Linq-To-DataSet, for example:
var timeSpans = dataSet.Tables[0].AsEnumerable()
.Select(r => new {
DurHour = r.Field<String>("Duration").Split(':')[0],
DurMinute = r.Field<String>("Duration").Split(':')[1]
})
.Select(x => new TimeSpan(int.Parse(x.DurHour), int.Parse(x.DurMinute), 0));
Console.WriteLine("Total time in minutes: {0}", timeSpans.Sum(ts=>ts.TotalMinutes));
But that is only a workaround, actually you should really avoid to store a timespan in a varchar column, use varchar only for text and nothing else.
In SQL-Server 2005 (or other dbms) you could also use two columns, one for the start DateTime and one for the end DateTime.
I have the following piece of code in C# that I use to select some rows from a SQL Server table based on a date criteria.
DateTime From, DateTime To
SqlParameter[] oParam = new SqlParameter[3];
oParam[0] = new SqlParameter("#From", From.Date);
oParam[1] = new SqlParameter("#To", To.Date);
DataTable dt = clsDatabaseHistory.ExecuteReader("SELECT * FROM tblHistory WHERE Date_Requested BETWEEN #From and #To", oParam);
If for example From=18/08/2011 and To=18/08/2011 and there is data in the table tblHistory that has the Date_Requested value as 18/08/2011 the query does not return it.
But if I change the value of To from 18/08/2011 to To=19/08/2011 the query returns me all the values from the table that have a Date_Requested value of 18/08/2011, but none from the 19/08/2011.
How can something like that be possible and what query should I use to return rows where the date field is between date1 and date2.
Something like :
select * rows where datevalue >= date1 and datevalue <= date2
Thank you.
Change your query to use >= and <
select * rows where datevalue >= date1 and datevalue < date2 + 1
I bet your Date_Requested in your table also has some time associated with it - so it probably really is 18/08/2011 14:37 or something like that.
The BETWEEN clause will be selecting anything between 18/08/2011 00:00:00 and 18/08/2011 00:00:00 - basically nothing.
What you need to take into account when working with DATETIME is the fact there's always also TIME involved!
If you want everything for today, you need to use:
BETWEEN `18/08/2011 00:00:00` AND `18/08/2011 23:59:59`
With those two values, you should get all rows with a Date_Requested of today.
OR: in SQL Server 2008 and newer, you could also use the DATE column type which stores date only - no time portion involved. In that case, you should be fine with your query values.
From.Date and To.Date gets the date portion on c# side ignoring the time portion; you need to do something similar on the database side.
Try
"SELECT * FROM tblHistory WHERE cast(Date_Requested as DATE) BETWEEN #From and #To"
to remove the time portion.
EDIT:
as explained in this answer, you could change #To param value to
oParam[1] = new SqlParameter("#To", To.Date.AddDays(1));
You need to account for time (not just date). One way I handle that is like this:
SELECT
...
WHERE CONVERT(varchar(8), date_begin, 112) <= convert(varchar(8), #to, 112)
This converts dates to YYYYMMDD format (with no time), which is very easy to use in <, >, = comparrisons.
Ok, thanks to you all, i've done the following thing
oParam[2] = new SqlParameter("#To", To.Date.AddDays(1));
and used the following select
SELECT * from MyTable WHERE CONVERT(varchar(8), Date_Requested, 112) >= CONVERT(varchar(8), #From, 112) and CONVERT(varchar(8), Date_Requested, 112) < CONVERT(varchar(8), #To, 112)
Datetime variables must be converted to be compared.
Thanks all!