Displaying dates values for current date in SQL Server - sql-server

I am trying to filter out the values based on the date which should be within today's date. I am using the below query, however the query is not working as expected.
This is what I am using in SQL Server.
select values
from table
where date between DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
and GETDATE()
I am expecting the date to be filtered for values between '2015-03-18 00:00:00' AND '2015-03-18 23:59:59' if I am executing the query on 18th March 2015.
Please guide.

It's much better to use a >= and < than BETWEEN:
SELECT *
FROM Table
WHERE
date >= CAST(CAST(GETDATE() AS DATE) AS DATETIME)
AND date < DATEADD(DAY, 1, CAST(CAST(GETDATE() AS DATE) AS DATETIME))
CAST(CAST(GETDATE() AS DATE) AS DATETIME) will get you the current date without the time part that is 2015-03-18 00:00:00
DATEADD(DAY, 1, CAST(CAST(GETDATE() AS DATE) AS DATETIME)) will get you the next day, again without the time part.
So in turn, your WHERE condition would be:
WHERE
date >= '2015-03-18 00:00:00'
AND date < '2015-03-19 00:00:00'
Alternatively, you can use this:
SELECT *
FROM Table
WHERE
date >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0) -- beginning of this day
AND date < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) + 1, 0) -- beginning of next day
For more date calculations, refer to this article.

As You are Expecting value between '2015-03-18 00:00:00' AND
'2015-03-18 23:59:59. so, you can simply compare only date part.
you can Use Cast()/Convert():
SELECT *
FROM Table
WHERE
cast(date as date) =cast(getdate() as date)
It included 2015-03-18 00:00:00' AND '2015-03-18 23:59:59'

Related

SQL Date Col - Use DATE or Varchar?

I have very simple code, but the issue is that when I convert a date column to Varchar(10), then I am not fetching distinct dates and sort is not working as desired; when I use DATE format, then I am fetching distinct dates and date sort is working, but I get datetime - 2017-02-01 12:00:00 AM (I don't want the time part)
Here is the code:
SELECT DISTINCT
--CONVERT(varchar(10), DATEADD(month, DATEDIFF(month, 0, (MyDate)), 0), 101) AS MonthValue,
CONVERT(DATE, DATEADD(month, DATEDIFF(month, 0, (MyDate)), 0)) AS MonthValue
FROM dbo.Mytable
WHERE MyDate >= GETDATE()-366
ORDER BY MonthValue DESC

SQL Server - Date String

Can you please help me create an sql statement that will get the previous date and concatenate that date in this format:
'2016-05-05 00:00:00'
I already know the sql function to get the previous date but I don't know yet on how to get the time in the expected format. My query is something like this
Select *
from table
where
transaction_date between '2016-05-05 00:00:00' and '2016-05-05 23:59:59'
So I need 00:00:00 and 23:59:59 to be concatenated in the date.
You don't need the times at all. Just don't use BETWEEN and use >= and < for the next day, like this:
SELECT *
FROM table
WHERE transaction_date >= '2016-05-05'
AND transaction_date < '2016-05-06'
Or if you only have the single date value:
DECLARE #date DATETIME = '2016-05-05'
SELECT *
FROM table
WHERE transaction_date >= #date
AND transaction_date < DATEADD(DAY, 1, #date)
The added benefit of doing it this way is that you also don't miss out on times that occur in the last second of the day as your original query does. For example 2016-05-05 23:59:59.001
Edit: From the comments below
To get yesterdays date, get today's date and subtract a day from it:
DECLARE #date DATETIME = DATEADD(DAY, -1, CAST(GETDATE() AS DATE))
Now use the logic as mentioned above.
This function:
DATEADD(dd, DATEDIFF(dd, 0, GetDate()), 0)
...will turn 2016-05-05 18:18:231 into 2016-05-05 00:00:000. From there it is easy to get full date boundaries by adding and subtracting days:
DECLARE #Date DATETIME
,#YesterdayStartDate DATETIME
,#TodayStartDate DATETIME
SET #Date = GetDate()
SET #TodayStartDate = DATEADD(dd, DATEDIFF(dd, 0, #date), 0)
SET #YesterdayStartDate = DATEADD(dd, -1, #TodayStartDate)
SELECT #Date, #YesterdayStartDate, #TodayStartDate
SELECT *
FROM Table
WHERE
transaction_date >= #YesterdayStartDate AND
transaction_date < #TodayStartDate
This will give you the result with transaction_date on yesterday.
SELECT
*
FROM
TABLE
WHERE
transaction_date BETWEEN dateadd(DAY, datediff(DAY, 1, GETDATE()), 0) AND dateadd(DAY, 1, dateadd(DAY, datediff(DAY, 1, GETDATE()), 0))
Compare date with out time part . ie below code.
Select * from table
where CONVERT(VARCHAR(8), transaction_date , 112) = CONVERT(VARCHAR(8), getdate(), 112)

SQL create a list of dates based on current date

I have a column of dates that range from 2015-06 to 2013-04. The date range will grow as I put in more data. How do I write a query where the date is always a X amount of months before the current date?
date
2015-06
2015-05
2015-04
2015-03
2015-02
for example I want it to be:
Select *
From dbo.name
Where date in (X months ago from current date)
if todays date is 2015-12 and I want 3 months ago, I want the query to be:
Select *
From dbo.name
Where date in ('2015-11','2015-10','2015-09')
Thanks
Select *
From dbo.name
Where CAST([Date] + '-01' AS DATE) >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) -3, 0)
Since your date strings are in yyyy-mm format you can do string comparison using < > =. You just need to convert the current date to varchar(7) using style 126 (yyyy-mm-ddThh:mi:ss.mmm)
For Example
DECLARE #CurrentDate DATETIME = GETDATE()
DECLARE #XMonthsAgo INT = 3
DECLARE #Dates TABLE ([date] varchar(7))
INSERT INTO #Dates VALUES
('2015-09'),('2015-08'),('2015-07'),('2015-06'),('2015-05'),('2015-04'),('2015-03'),
('2015-02'),('2015-01'),('2014-12'),('2014-11'),('2014-10'),('2014-09'),('2014-08'),
('2014-07'),('2014-06'),('2014-05'),('2014-04'),('2014-03'),('2014-02'),('2014-01')
SELECT *
FROM #Dates d
WHERE [date] >= CONVERT(VARCHAR(7), DATEADD(month, -#XMonthsAgo, #CurrentDate), 126)
AND [date] < CONVERT(VARCHAR(7), #CurrentDate, 126)
Result
date
----
2015-07
2015-06
2015-05

Get date with some criteria in SQL server

What I want is the EmployeeName from the emp_mst table with some condition which is given below:-
All EmployeeName for last 7 months from the current date and also less 15 days.
from the below query I am getting the result for the last month, but I want this for the last 6 months
select DATEADD(month, -1, GETDATE()- 15)
I am using sql server 2008
UPDATED PROCEDURE
SELECT * FROM (SELECT CASE
WHEN (SELECT Isnull(Sum(total_day), 0)
FROM xxacl_erp_ab_pl_count_view
WHERE emp_card_no = em.emp_card_no) > 7 THEN
'DOC Exteded By 1 month. Reason:- Taken leave='
+ CONVERT(VARCHAR, (SELECT Sum(total_day) FROM
xxacl_erp_ab_pl_count_view
WHERE emp_card_no = em.emp_card_no))
+
' which is > 7. Actual DOC='
+ CONVERT(VARCHAR, Dateadd(mm, em.probation_period, em.date_of_joining), 103)
+ ''
ELSE 'N/A'
END Remark,
em.*
FROM emp_mst em
LEFT JOIN company_mst comp
ON em.comp_mkey = comp.mkey
AND comp.fa_year = 2008
AND company_name NOT LIKE '%HELIK%'
WHERE em.status IN ( 'A' ) --and em.emp_type='E'
AND em.emp_card_no != 9999
AND em.resig_date IS NULL
AND CONVERT(DATETIME, em.date_of_joining, 103) >=
CONVERT(DATETIME,
Dateadd(m, -6, Getdate()), 103)
AND em.emp_card_no NOT IN (SELECT emp_card_no
FROM p_emp_confirmation_hdr
WHERE delete_flag = 'N'
AND hr_flag = 'Y')) pp
WHERE remark = 'N/A'
Casting to date to avoid calculating with timestamps
WHERE
yourdate >= dateadd(m, -6, datediff(d, 15, getdate())) and
yourdate < dateadd(d, -15, datediff(d, 0, getdate()))
Changed answer to adjust for you using sqlserver 2005 or older
Added 15 days extra to the interval
SELECT [emp_name]
FROM [TABLE]
WHERE [DateColumn] BETWEEN DATEADD(MONTH, -6, CAST(GETDATE() AS DATE))
AND DATEADD(DAY, -15, CAST(GETDATE() AS DATE))
This will show you employees who were added between six months ago and 15 days ago, for example, running that today would give you employees from the range 2014-12-24 and 2015-06-09.
EDIT: For SQL Server 2005 and earlier:
SELECT [emp_name]
FROM [TABLE]
WHERE [DateColumn] BETWEEN DATEADD(MONTH, -6, cast(convert(char(11), getdate(), 113) as datetime))
AND DATEADD(DAY, -15, cast(convert(char(11), getdate(), 113) as datetime))

Retrieve rows from a certain day but only in a certain hour

I have a query which returns all of the rows for three days ago:
SELECT * FROM table2
WHERE CONVERT(date, given_schedule)
= CONVERT(date, DATEADD(d, -3, GETDATE()))
But I want to know limit the rows to only the hour relative to the current time. So for example, it is currently after 9:00 PM then I only want to retrieve the rows that occurred three days ago and between 9:00 and 10:00 PM.
SELECT columns FROM dbo.table2
WHERE
CONVERT(DATE, given_schedule)
= CONVERT(DATE, DATEADD(DAY, -3, CURRENT_TIMESTAMP))
AND
DATEPART(HOUR, given_schedule)
= DATEPART(HOUR, CURRENT_TIMESTAMP);
To address #Habo's point, you could also do:
DECLARE #s SMALLDATETIME = CURRENT_TIMESTAMP;
SET #s = DATEADD(DAY, -3, DATEADD(MINUTE, -DATEPART(MINUTE, #s), #s));
SELECT columns FROM dbo.table2
WHERE given_schedule >= #s
AND given_schedule < DATEADD(HOUR, 1, #s);
This is, of course, most useful if there is actually an index with given_schedule as the leading column.
You could use the DATEDIFF function and pass in hour as the datepart argument.
SELECT * FROM table2 WHERE DATEDIFF(hour, GETDATE(), given_schedule,) BETWEEN 0 AND 1
See this for more info.

Resources