SQL Select Query for Date Conversion - sql

Have been researching all day and so far not found an acceptable answer and my experimenting with code has yielded nothing.
I've got a database with a particular 2 columns "StartDate" and "LastBackupDate" which seem to be storing their date information as a Julian date (eg. 40953.6017873071). I need to convert this to a standard Gregorian Date (MM-DD-YYYY or DD-MM-YYYY).
I'm pulling back all results from this table at current "Select * FROM xxxxxx WHERE blah blah".
I'm able to convert these dates in no time with Excel, if I export the data to a sheet, but when I pull the data with Convert, I'm unable to get the date converted.
This is part of a SQL query for a webpage. I can't post out the webcode, but I can post the SQL query:
SELECT * FROM ExpandedCustomerView WHERE regloginid = #0 AND (Status='A' OR Status='H')"
I've been experimenting with this:
SELECT CONVERT(varchar(36),[STARTDATE],101)
[StartDate]
,[LastBackupDate]
FROM [CNTD_Accounts].[dbo].[ExpandedCustomerView]
As a way to get this returned appropriately. I've tried formatting of 101, 110 and others to see if we can get the right results. So far, nothing is working for me. I think this has to be fairly simple.

Cast from number to datetime directly..
select cast(40953.6017873071 as datetime)
--
2012-02-16 14:26:34.423
e.g.
cast([StartDate] as datetime)
If the data is a number in a varchar field, cast it twice
cast(cast([StartDate] as float) as datetime)

Related

How do I get the date from a datetime when creating a SQL view?

I have searched for hours and found a lot of information about how do convert a datetime field to a date. All of it works well in my SQL window. However, the minute I try to use in in a view it crashes.
Version: SQL Server v17.0
Example:
field in the table is: InvoiceDate(datetime,null)
data is: 2016-11-15 00:00:00.000
my SQL code is:
CONVERT(date,ihhd.InvoiceDate,101) AS InvoiceDate
my InvoiceDate result is: 2016-11-15
when I put that same code into a view I get this:
SQL Execution Error.
Executed SQL SELECT [selected fields]
Error Source: .Net SqlClient Data Provider
Error Message: Cannot call methods on date.
I've tried to convert it to a varchar:
CONVERT(varchar,ihhd.InvoiceDate,101) AS InvoiceDate
that does not return the same error in the view window. However,the report writer that will use this data does not allow "date-like" comparisons so I need the field in a date format.
I also tried do double convert it:
CONVERT(date,CONVERT(varchar,ihhd.InvoiceDate,101),101) AS InvoiceDate
again the SQL window was OK with it and the view window threw up the same error.
What am I doing wrong?
Your are converting a DATETIME to a DATE so it will produce the expected yyyy-mm-dd. You need to convert to a string if you want MM/DD/YYYY. Keep in mind this converted string is NOT a date, and should really be relegated to the presentation layer.
Select AsString = convert(varchar(10),GetDate(),101) -- notice the varchar(10)
,AsDate = convert(date,GetDate(),101)
Returns
AsString AsDate
06/14/2017 2017-06-14
Conversely, you can take a MM/DD/YYYY string and convert to a date
Select convert(date,'06/14/2017',101) -- If 2012+ try_convert()
Returns
2017-06-14
Unreproducible.
I just tested this code on the datetime column in an existing table:
CREATE VIEW vDT
AS
SELECT CONVERT(date, [StartTime],101) AS tDate
FROM [dbo].[Trace20150811];
I got no error, and was able to SELECT from the view afterwards and get expected results.
Go over your code more carefully, because the real reason you are getting the error is not in the code you posted. If you cannot find it, post your complete view code without changing anything.
I've had this exact same problem for years. The code works fine in a query window, stored proc, etc but when I use it in a View it errors out. In a View, the CONVERT function works for other data types but it won't allow you to convert to Date type. If I CONVERT to VARCHAR(10) then it looks fine but if you use Crystal or Excel to retrieve the data it doesn't see that field as a Date type and therefore you can't do date filtering.

Casting varchar as date

I think I've read just about every thread on this topic and none of them are solving my problem.
First of all, the database I'm working with has all date fields set to a varchar data type, which drives me insane because I constantly have to cast or convert whenever I'm working with any queries involving dates.
The query I'm working with at the moment is supposed to pull a list of medical patients who all have a certain diagnosis, but that diagnosis has to have been given before a certain date. Here's what I've got.
SELECT DISTINCT
pd.PatientID,
pd.PatientName,
pmh.DateOfOnset
pmh.DiagnosisCode
FROM PatientDemographic pd JOIN PatientMedicalHistory pmh ON pd.PatientID = pmh.PatientID
WHERE pmh.DiagnosisCode = '401.1'
AND CAST(pmh.DateOfOnset as Date) > CAST('12/31/2014' as Date)
I'm getting an error that says "Conversion failed when converting date and/or time from character string." It's telling me the error is on Line 1 though (the SELECT DISTINCT line) so that's not really helpful and I'm not sure what I need to fix.
As I mentioned, the DateOfOnset field has a varchar data type, and I need to find any of those dates that came before the end of December, 2014. I've tried to remedy this error by trying different combinations of the CAST statements -- I even tried including a cast on the date field in the SELECT statement, and I'm still getting the same error.
I was working on another query earlier that required me to find all patient appointments from within a certain time frame, and for that query, I had my WHERE clause set up like:
WHERE Cast(VisitDate as Date) BETWEEN CAST('01/01/2014' as Date) AND CAST('12/01/2014' as Date)
...and it worked perfectly fine. Since I've got my current query set up virtually the same way, I'm not sure why I'm getting that conversion error.
You have wrong dateformat:
SET DATEFORMAT dmy;
SELECT CAST('12/31/2014' as Date);
--Conversion failed when converting date and/or time from character string.
You could set it to mdy before executing your query.
SET DATEFORMAT mdy;
SELECT CAST('12/31/2014' as Date);
LiveDemo
or use CONVERT with style 101:
SET DATEFORMAT dmy;
SELECT CONVERT(DATE,'12/31/2014',101)
If you really need to store DATE as VARCHAR use at least culture independent type like ISO-8601.
SET DATEFORMAT dmy;
SELECT CAST('20140201' as Date);
-- 01.02.2014
SET DATEFORMAT mdy;
SELECT CAST('20140201' as Date)
-- 01.02.2014
It sounds like SQL is not able to convert the stored strings into dates. This would explain why CAST(pmh.DateOfOnset as Date) fails where Cast(VisitDate as Date) does not--the latter might not have any mis-formatted dates.
Best-case solution is to convert your table columns to the proper datatypes. Second-best case, add columns containing the proper datatypes, and convert the data over; you'd have to fix any existing bad data, as well as convert data on the fly as it's loaded (yuck). Another option, add a calculated column, though you'll have problems with the afore-mentioned invalid dates. (What version of SQL do you have? Later versions have the isdate function, which might help here.)
If modifying tables is not an option, you're probably stuck writing queries that have to assume some of the data is invalid (bad format).

Comparing dates in SQL returns wrong records

I am trying to locate a date in database between two specific dates entered by user. Something like:
SELECT date FROM table WHERE date>=dateFrom AND date<=dateTO
I have the following table:
I have made a mistake saving the date as VARCHAR and now i have to do all the str_to_date and date_format as i am using phpMyAdmin. I somehow did it but i am facing this strange problem using this query:
SELECT date_format(str_to_date(data,'%d/%m/%Y'),'%d/%m/%Y') AS data FROM montaggio WHERE data>=date_format(str_to_date('29/08/2014','%d/%m/%Y'),'%d/%m/%Y')
The query would return to me only the date 19/08/2014 where as i expected it to return 01/09/2014. On the other hand if it enter the query
SELECT date_format(str_to_date(data,'%d/%m/%Y'),'%d/%m/%Y') AS data FROM montaggio WHERE data>=date_format(str_to_date('29/08/2014','%d/%m/%Y'),'%d/%m/%Y') AND data<=date_format(str_to_date('05/09/2014','%d/%m/%Y'),'%d/%m/%Y')
The query returns nothing.
I am using phpMyAdmin.
What am i missing here? Any help would be appreciated!
You do seem a bit confused. All the operations on dates should be done on the date data type. There is no need to convert things back to strings:
SELECT data
FROM montaggio
WHERE str_to_date(data, '%d/%m/%Y') >= str_to_date('29/08/2014', '%d/%m/%Y')
You seem to understand the real solution, which is to store dates/times in the database using the correct type. If you have to use strings for dates, then always stored them as YYYY-MM-DD, so comparisons and sorting will work correctly.

MsSQL - Return results within a date range

I was wondering if someone could help me out.
I need to return database results based on a date range, im using Classic ASP and MsSQL
My script gives me dates formatted as follows:
6/18/2014
The dates are saved in the database in the following format
12/24/2014 7:03:00 AM
What im wanting to do is something as follows:
SELECT * FROM table WHERE paid >= 6/18/2014 AND =< 6/28/2014
When i run that, im getting weird results as the dates arent formatted the same.
Can someone help me out.
Cheers,
you should put those two dates between single quotes like..
SELECT * FROM table WHERE paid BETWEEN '6/18/2014' and '6/28/2014'
EDIT:
you can use DATE_FORMAT(date,format) function to display date/time data in different formats.
here's some reference
http://www.w3schools.com/sql/func_date_format.asp
if its not typo
SELECT * FROM table WHERE paid BETWEEN '6/18/2014' AND '6/28/2014'
EDIT:-my database is storing it in the format yyyy-mm-dd
SELECT *
FROM table
WHERE DATE >= '2014-05-18'
AND DATE <= '2014-06-28'
and its working correctly
here is a reference
change the format according to your own database it will work

How to use between clause for getting data between two dates?

I have date field in the database in the format 2012-03-17 19:50:08.023.
I want to create a select query which gives me the data collected in the March month.
But I am not able to achieve this.
I am trying following query.
select * from OrderHeader where
Convert(varchar,UploadDt,103) between '01/03/2013' and '31/03/2013'
and DistUserUniqueID like '6361%'
This query gives me data for all the dates.
select * from OrderHeader where
UploadDt between '01/03/2013' and '31/03/2013' and DistUserUniqueID like '6361%'
This query gives me the error as Msg 242, Level 16, State 3, Line 1
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
Please help me resolve this.
Thanks in advance
The first query returns all dates because you are converting your column to a string. Not sure why you are doing this. So when you say BETWEEN '01/anything' AND '31/anything', when you consider it is now just a string, that is going to match all "dates" in the column, regardless of month and year, since your WHERE clause will cover every single day possible (well, with the exception of the 31st of months other than March, and the first day in January and February - so not all the data but a very large percentage). '15/11/2026', for example, is BETWEEN '01\03\2013' AND '31/03/2013'.
Think about that for a second. You have datetime data in your database, and you want to convert it to a string before you query it. Would you also convert salary to a string before comparing it? If so, the person making $70,000 will look like they are making more than the person making $690,000, since character-based sorting starts at the first character and doesn't consider length.
The second query fails because you are using a regional, ambiguous format for your dates. You may like dd/mm/yyyy but clearly your server is based on US English formatting where mm/dd/yyyy is expected.
The solution is to use a proper, unambiguous format, such as YYYYMMDD.
BETWEEN '20130301' AND '20130313'
However you shouldn't use BETWEEN - since this is a DATETIME column you should be using:
WHERE UploadDt >= '20130301'
AND UploadDt < '20130401'
(Otherwise you will miss any data from 2013-03-31 00:00:00.001 through 2013-03-31 23:59:59.997.)
If you really like BETWEEN then on 2008+ (you didn't tell us your version) you can use:
WHERE CONVERT(DATE, UploadDt) BETWEEN '20130301' AND '20130331'
More date-related tips here:
Dating Responsibly
Finally, when converting to VARCHAR (or any variable-length data types), always specify a length.
Rewrite the query as
select * from OrderHeader where
UploadDt between '01/03/2013' and '01/04/2013'
and DistUserUniqueID like '6361%'
or
select * from OrderHeader where
UploadDt between Convert(datetime,'01/03/2013', 103) and Convert(datetime,'01/04/2013',103)
and DistUserUniqueID like '6361%'