slice data between the range of dates SQL Server - sql-server

I am having a miserable time in achieving a simple task. I want to slice data for every 6-months every month. I am not getting any output. My SQL skills are very bad. I searched for the solution a lot and they gave me some idea but I am not able to any output.
Below is my attempt:
SELECT TOP 10000 CONVERT(VARCHAR,DATEADD(HOUR,-4,DATEADD(s, ch.dateTimeOrigination, '19700101')), 121) as CallDate
FROM [dbo].[CallData] AS ch
WHERE LEN(ch.callingPartyNumber) = 4 AND
CONVERT(VARCHAR,DATEADD(HOUR,-4,DATEADD(s, ch.dateTimeOrigination, '19700101')), 121) BETWEEN CONVERT(VARCHAR(10), GETDATE(), 110) AND CONVERT(VARCHAR(10), DATEADD(month, -6, GETDATE()), 110)
The table definitely has the data for the time period I am trying to query. So I am not sure why this is not giving me any output. I will really appreciate your help. Thank you.

I believe your BETWEEN values are backwards.
EDIT: Your CONVERT statements in the WHERE clause are also different formats, so when you compare your varchars, the comparison fails. You should instead use DATETIME.
Try this:
SELECT TOP 10000
CONVERT(VARCHAR,DATEADD(HOUR,-4,DATEADD(s, ch.dateTimeOrigination, '19700101')), 121) as CallDate
FROM [dbo].[CallData] AS ch
WHERE LEN(ch.callingPartyNumber) = 4 AND
CAST(DATEADD(HOUR,-4,DATEADD(s, ch.dateTimeOrigination, '19700101')) AS DATETIME) BETWEEN DATEADD(month, -6, GETDATE()) AND GETDATE()

Related

SQL Server: datediff function resulted in an overflow when using MILLISECOND

I have the following query :
select CONVERT(varchar(12), DATEADD(MILLISECOND, DateDiff(MILLISECOND, '2014-08-04 10:37:28.713','2014-11-04 08:21:17.723'), 0), 114)
When I execute this, I get the error :
"The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart."
When I change the query to the following it works fine :
select CONVERT(varchar(12), DATEADD(SECOND, DateDiff(SECOND, '2014-08-04 10:37:28.713','2014-11-04 08:21:17.723'), 0), 114)
The problem is that I really need the MILLISECONDS as well.
A bit later response but may help.
In SQL 2016 MS introduced function DATEDIFF_BIG which will (according to type size) overflow in difference bigger than something like 290k years. But technet article have same time difference as basic DATEDIFF - https://msdn.microsoft.com/en-us/library/mt628058.aspx
See https://learn.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql?view=sql-server-ver15#return-value
For millisecond, the maximum difference between startdate and enddate is 24 days, 20 hours, 31 minutes and 23.647 seconds.
If you need millisecond above that level, you'll need to write something custom.
In SQL Server 2016 there is a new function available: DATEDIFF_BIG
It solves exactly the overflow problem.
You don't need to refer to the miliseconds in your calculation.
This will do exactly the same as your script except the overflow:
SELECT CONVERT(varchar(12),
CAST('2014-11-04 08:21:17.723' as datetime) -
CAST('2014-08-04 10:37:28.713' as datetime)
, 114)
For me there was a big interval between two dates so i have used below code
declare #timetagInMillsecond bigint=CAST(CAST( cast(#timetag as
datetime) -'1970-01-01' AS decimal(38,10))*24*60*60*1000+0.5 as
bigint)
It works for me .
Use DATEDIFF_BIG to resolve the overflow issue
The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.
SELECT DATEDIFF_BIG(
millisecond,
SYSDATETIME(),
DATEADD(year, 1000, SYSDATETIME()) ) AS 'Milliseconds in 1000 years';
For SQL Server 2014, the following works around the 'int' limitation to obtain a "JavaScript Time Epoch". This assumes the start epoch is itself a date, which fits the local use-case leading to finding this question. The query requires adaptation to the specific question use-case which does not have this property.
declare #x as datetime = getdate()
-- epoch_delta_s_to_date * 1000 + day_delta_ms
select
cast(datediff(second, '1970-01-01', cast(#x as date)) as bigint) * 1000
+ cast(datediff(millisecond, cast(#x as date), #x) as bigint)
For the case of obtaining a "JavaScript Time Epoch" this is still subject to the Y2038 limitation of datediff(second, '1970-01-01', ..).

Date conversion error in SQL on one Computer, but the code works on another?

I have this piece of Code
Select * FROM [DB].[dbo].[STG_TABLE]
WHERE convert(datetime, cast([CHANGE_DATE] as char(8))) > DATEADD(DAY, -3, GETDATE())
The CHANGE_DATE is of type numeric(8,0).
I have used this code before. It still works on my local machine on the same data, but when I run this on the Development server, it gives an error:
Conversion failed when converting date and/or time from character string.
Both computers has the same system date settings in the Control panel.
If I remove the convert, like so:
Select * FROM [DB].[dbo].[STG_TABLE]
WHERE cast([CHANGE_DATE] as char(8)) > DATEADD(DAY, -3, GETDATE())
it gives the same error which leads me to believe it is after the greater than, but I still don't know why.
Try another convert.
Select * FROM [DB].[dbo].[STG_TABLE]
WHERE [CHANGE_DATE] > cast(convert(char(8),DATEADD(DAY, -3, GETDATE()),112) as numeric(8,0))
GetDate() -> CHAR(8) -> NUMERIC and then compare to table field
Also try to check dates in your table
SELECT [CHANGE_DATE]
from [DB].[dbo].[STG_TABLE]
where isdate(cast([CHANGE_DATE] as char(8)))=0

SQL Server between two datetime fields, not working correctly

SQL Server 2005:
The following view
SELECT CONVERT(VARCHAR(20), keyedtimestamp, 101) as KeyedDate
FROM TMSSTATFILE_STATS a
WHERE (CONVERT(VARCHAR(20), a.KeyedTimestamp, 101) BETWEEN '03/01/2011' And '03/31/2011')
ORDER BY KeyedDate
Results are given for keyed dates 3/2/2011 to 3/31/2011.
If I change the first date to 03/00/2011
SELECT CONVERT(VARCHAR(20), keyedtimestamp, 101) as KeyedDate
FROM TMSSTATFILE_STATS a
WHERE (CONVERT(VARCHAR(20), a.KeyedTimestamp, 101) BETWEEN '03/00/2011' And '03/31/2011')
ORDER BY KeyedDate
it now gives data for dates 3/1/2011 to 3/31/2011
The KeyedTimestamp field is DateTime and there are times associated with these records. All records for 3/31/2011 are accounted for. I know I can do this instead by supplying the max time in the second date in between, so I'm not looking for an alternative where clause, but rather an understanding of why it's ignoring the records from the first even though its incorporating the ones from the 31st.
Its almost as if its checking for 3/1/2011 23:59:59, I was hoping I could eliminate this kind of check where I only care about the date, not the time
Avoid a function on the column by not using BETWEEN. A function mean any index will never be used
WHERE
a.KeyedTimestamp >= '20110301' AND a.KeyedTimestamp < '20110401'
And pre-SQL Server 2008 yyyymmdd is the only safe date format.
You shouldn't be converting the datetimes to strings. Instead, compare them as datetimes. It sounds like you are trying to get around the problem of times being stored:
Select DateAdd(d, DateDiff(d, 0, T.KeyedTimeStamp), 0) As KeyedDate
From TMSSTATFILE_STATS As T
Where T.KeyedTimeStamp >= '20110301'
And T.KeyedTimeStamp < DateAdd(m,1,'20110301')
It should be noted that DateTimeVal Between DateTimeA And DateTimeB translates to DateTimeVal >= DateTimeA And DateTimeVal <= DateTimeB. I.e., it is inclusive of both end points. In the above solution, I'm getting the first day of the following month and asking for all values strictly less than that value which means all values in the month of March, including times, will be included. Finally, the Select statement is stripping the time value from all return KeyedTimeStamp values.
Have you tried converting to DATETIME values (or similar) and then comparing? You're comparing strings... I don't know what '03/00/2011' means, conceptually, to the BETWEEN operator. Frankly, I'm surprised that your results make any sense at all!
SQL Server 2008 has a native DATE type, which excludes timestamps.
If you do not have a native type (you mentioned V9) without a timestamp you can use something like this:
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, your_date_here))
As taken from Anatoly Lubarsky's blog:
http://blogs.x2line.com/al/archive/2006/02/17/1458.aspx
Datetime compares isn't coming into it, everything is VARCHAR while you are comparing.
Try:
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, keyedtimestamp)) as KeyedDate
FROM TMSSTATFILE_STATS a
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, keyedtimestamp)) BETWEEN '03/01/2011' AND '03/31/2011'
ORDER BY DATEADD(dd, 0, DATEDIFF(dd, 0, keyedtimestamp))

Remove time from DateTime sql server 2005

I need date part from datetime. in format of "dd-mm-yyyy"
I have tried follwoing
Query:
select Convert(varchar(11), getdate(),101)
Output:
01/11/2011
Query
SELECT cast(floor(cast(GETDATE() as float)) as datetime)
Output
2011-01-11 00:00:00.000
Query:
SELECT
CONVERT(VARCHAR(MAX),DATENAME(DD,GETDATE())) + '-' +
CONVERT(VARCHAR(MAX),DATEPART(MONTH,GETDATE())) + '-' +
CONVERT(VARCHAR(MAX),DATENAME(YYYY,GETDATE())) `
Output:
11-1-2011 i.e. "d-m-yyyy"
I required output in "dd-mm-yyyy" format.
SELECT CONVERT(VARCHAR(10),GETDATE(),105)
Try:
SELECT convert(varchar, getdate(), 105)
More here.
Here you can find some examples how to do this: http://blog.pengoworks.com/index.cfm/2009/1/9/Useful-tips-and-tricks-for-dealing-with-datetime-in-SQL
Using the CONVERT function "works" but only if you're comparing strings with strings. To compare dates effectively, you really need to keep the SMALLDATETIME data type strongly typed on both side of the equation (ie "="). Therefore 'apros' comment above is really the best answer here because the blog mentioned has the right formulas to use to strip off the time component by "flattening" it to midnight (ie 12:00:00) via rounding and any date column in SQL Server 2005 will always default to 12:00:00 if the date is given without a time.
This worked for me ...
select dateadd(day, datediff(day, '20000101', #date), '20000101')

Need only Date from DateTime

I have a variable of DateTime type in SQL.
Just need to have Date part of it.
please Help?
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
The result is: “2009-07-14 00:00:00.000”
Edit: guess the next variant is more common:
SELECT DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
because of the day pattern can be easily changed to week or month pattern. It is very useful when the GROUP BY clause should group by week of month (reports).
This has been asked and answered before on Stack Overflow. In fact, it's been asked over and over:
Most efficient way in MS SQL to get date from date+time?
Best way to check for current date in where clause of sql query.
SQL Drop Time in DateTime
MS SQL Date Only Without Time
How to return the date part only from a SQL Server datetime datatype
Found this using Google
SELECT CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, GETDATE())))
If you just need a varchar representation of the date, you can use the convert function, e.g.
select convert(varchar, getDate(), 102) /* 2009.07.14 */
If you need a datetime (midnight on the given date), you can just convert it back.
select convert(datetime, convert(varchar, getDate(), 102), 102)
-- Sneaky CAST/DATEDIFF trick strips off the time to get just the day (midnight)!
CAST(DATEDIFF(d,0,DateField) AS DATETIME) AS DayField
SQL Server 2008 has a date datatype that stores just the date, if you are inthis version, perhaps this would be a better datat type for you to use. Be warned though, Date doesn't work exactly like datetime for data manipulation.
SELECT DATEADD(day, DATEDIFF(day, '19900101', CURRENT_TIMESTAMP), '19900101')
A very useful article:
"The purpose of this article is to explain how the datetime types work in SQL Server, including common pitfalls and general recommendations."The ultimate guide to the datetime datatypes
Note that converting to varchar and back (convert(datetime, convert(varchar, getDate(), 102), 102)) is much slower.
If you want the format 'MM/DD/YY', use "CONVERT(varchar, #datetimevalue, 1) to display just the date. If you need it in datetime format, use "CONVERT(datetime, CONVERT(varchar, #datetimevalue, 1))".
I created an entry in my SQL blog about how to retrieve and display all possible formats of the CONVERT(varchar, ..) function:
http://jessesql.blogspot.com/2009/04/converting-datetime-values-to-varchar.html
A tip:
If you find yourself doing this often, you can create a scalar User Defined Function containing the time-stripping logic of your choice.
Be warned: SQL Server 2000 has some painful bugs involving UDF's in ON clauses.
datepart(day, datetimevalue)

Resources