Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query - sql

I have a table with a column that stores the date and time. I need to write a query to get only the date from that column,
SELECT CAST(CONVERT(VARCHAR, LoginTime, 101) AS datetime) FROM AuditTrail
But, when I run the query I am getting this error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
the data in the column is datetime ex: 2012-06-18 12:08:04.000
so i need to extract the date only and remove the time
note that the [Logintime] column is datatime format

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
WHERE ISDATE(LoginTime) = 1
Click here to view result
EDIT :
As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT
SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail
or
SELECT LEFT(LoginTime,10) FROM AuditTrail
EDIT 2 :
The major reason for the error will be in your date in WHERE clause.ie,
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('06/18/2012' AS DATE)
will be different from
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('18/06/2012' AS DATE)
CONCLUSION
In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

hope this may help you:
SELECT CAST(LoginTime AS DATE)
FROM AuditTrail
If you want to have some filters over this datetime or it's different parts, you can use built-in functions such as Year and Month

as you can see on the answer to this question:
Conversion of a varchar data type to a datetime data type resulted in an out-of-range value
-- set the dateformat for the current session
set dateformat dmy
-- The conversion of a varchar data type
-- to a datetime data type resulted in an out-of-range value.
select cast('2017-08-13 16:31:31' as datetime)
-- get the current session date_format
select date_format
from sys.dm_exec_sessions
where session_id = ##spid
-- set the dateformat for the current session
set dateformat ymd
-- this should work
select cast('2017-08-13 16:31:31' as datetime)

I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.
The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.

some problem, but I find the solution, this is :
2 February Feb 28 (29 in leap years)
this is my code
public string GetCountArchiveByMonth(int iii)
{
// iii: is number of months, use any number other than (**2**)
con.Open();
SqlCommand cmd10 = con.CreateCommand();
cmd10.CommandType = CommandType.Text;
cmd10.CommandText = "select count(id_post) from posts where dateadded between CONVERT(VARCHAR, #start, 103) and CONVERT(VARCHAR, #end, 103)";
cmd10.Parameters.AddWithValue("#start", "" + iii + "/01/2019");
cmd10.Parameters.AddWithValue("#end", "" + iii + "/30/2019");
string result = cmd10.ExecuteScalar().ToString();
con.Close();
return result;
}
now for test
lbl1.Text = GetCountArchiveByMonth(**7**).ToString(); // here use any number other than (**2**)
**
because of check **February** is maxed 28 days,
**

Related

Convert Varchar field to datetime in SQL Server

I am trying to convert varchar date to date time field and having a really hard time. It is giving me:
Conversion failed when converting date and/or time from character string.
or
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I have 2 datetime formats below :
Date field looks like 21-12-2009, 05-10-2005 etc
Date field looks like 19-03-2018 14:59
select cast(convert(varchar,Stg_hw.date_of_birth,110)as date)
from Stg_Height_and_Weight Stg_hw
where Stg_hw.person_id = 1620458
select CONVERT(datetime,LEFT(date_of_birth,2)+SUBSTRING(Stg_hw.date_of_birth,4,2)+SUBSTRING(Stg_hw.date_of_birth,7,4))
from Stg_Height_and_Weight Stg_hw
where Stg_hw.person_id = 1620458
select cast(Stg_hw.date_of_birth as date)
from Stg_Height_and_Weight Stg_hw
where Stg_hw.person_id = 1620458
CONVERT(DATETIME, DateFieldColumnName, 103) can help to convert those 2 format to datetime.
Sample exection:
CREATE TABLE TestTable (DateVal VARCHAR (20));
INSERT INTO TestTable (DateVal) VALUES
('21-12-2009'), ('05-10-2005'), ('19-03-2018 14:59');
SELECT CONVERT(DATETIME, DateVal, 103) AS Result
FROM TestTable
Please find the working demo on db<>fiddle

date time stored as varchar in sql how to filter on varchar

I am working on a project in which dates and times ar stored as a varchar e.g. "30-11-2017,7:30" first date in dd-mm-yyy format and then time separated with a comma. I am trying to filter on it but it is not working correctly kindly guide me how to filter data on date.
select *
from timetrack
where startDateAndTime >= '30-11-2017,7:30'
In attached image records have been shown. When I apply above query it shows no records
You can easily convert your date to SQL datatype datetime uisng parse function, for example select parse('30-11-2017,7:30' as datetime using 'it-IT').
So, in your case, you can apply this function in where clause, so you can easily apply comparison between dates:
select *
from timetrack
where parse(startDateAndTime as datetime using 'it-IT') >= '2017-11-30 07:30:00.000'
Your format is apparently italian :) But you have to specify your own date in the format convertable to datetime, as I have done in above example.
NOTE: parse is available starting with SQL Management Studio 2012.
Unless you are using ISO date format (yyyy-MM-dd HH:mm:ss or close) applying ordering (which inequalities like greater than or equal use) will not work: the date order is disconnected from the string ordering.
You'll need to parse the date and times into a real date time type and then compare to that (details of this depend on which RDBMS you are using).
If, you want to just filter out the date then you could use convert() function for SQL Server
select *
from timetrack
where startDateAndTime >= convert(date, left(#date, 10), 103)
Else convert it to datetime as follow
select *
from timetrack
where startDateAndTime >= convert(datetime, left(#date, 10)+' ' +
reverse(left(reverse(#date), charindex(',', reverse(#date))-1)), 103)
You need the date in a datetime column, Otherwise you can't filter with your current varchar format of your date.
Without changing the existing columns, this can be achieved by making a computed column and making it persisted to optimize performance.
ALTER TABLE test add CstartDateTime
as convert(datetime, substring(startDateAndTime, 7,4)+ substring(startDateAndTime, 4,2)
+ left(startDateAndTime, 2) +' '+ right(startDateAndTime, 5), 112) persisted
Note: this require all rows in the column contains a valid date with the current format
Firstly, you need to check what is the data that is entered in the 'startDateAndTime' column,then you can convert that varchar into date format
If the data in 'startDateAndTime' column has data like '30-11-2017,07:30', you would then have to convert it into date:
SELECT to_date('30-11-2017,07:30','dd-mm-yyyy,hh:mm') from dual; --check this
--Your query:
SELECT to_date(startDateAndTime ,'dd-mm-yyyy,hh:mm') from timetrack;

finding data lying between a specific date range in sql

I want to find records from my database which lie between any user input date range(say between 10/2/2008 to 26/9/2024). I tried using
SELECT NAME
,TYPE
,COMP_NAME
,BATCH_NO
,SHELF
,MFG_DATE
,EXP_DATE
,QTY
,VAT
,MRP
FROM STOCK_LOCAL
WHERE
convert(VARCHAR(20), EXP_DATE, 103)
BETWEEN convert(VARCHAR(20), #MEDICINEEXP_DATE, 103)
AND convert(VARCHAR(20), #MEDICINEEXPDATE, 103)
but with this query i need to enter perfect date range which is available in my database, it is not giving me data lying in between any date entered.
Thanks in advance
Since it is a poolr designed schema there isnt going to be any decent/Efficient solution for this.
In sql server if you are storing Date or Date & Time data. Use the Data or DATETIME datatypes for your columns.
In your case you are trying to compare a string with passed date. and even when you tried to convert the string (Date) into date datatype you didnt do it correctly.
My suggestion would be Add new columns to your table with Date datatype and update these columns with existing date/string values.
For now you can convert the Date(string) into date datatype using the following code.
DECLARE #MEDICINEEXP_DATE DATE = 'SomeValue1'
DECLARE #MEDICINEEXPDATE DATE = 'SomeValue1'
SELECT query....
FROM TableName
WHERE
CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) >= #MEDICINEEXP_DATE
AND CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) <= #MEDICINEEXPDATE
Note
This solution will get you the expected results but very inefficient method. It will not make use of any indexses on your EXP_DATE Column even if you have a very buffed up index on that column.

Convert from nvarchar to DateTime with am pm?

In my table I have myDate column of type nvarchar(50).
The result I need is to select this date/time: 07/11/2013 11:22:07
And I need to get 07/11/2013 11:22:07 am from it (add am/pm to the original date&time).
I tried everything but get only the original data without am/pm.
This is an example from my query :
select convert(dateTime,myDate,100) as Date from Info
or
select convert(dateTime,myDate,0) as Date from Info
What am I missing ?
try this !!
declare #date datetime
set #date='07/11/2013 11:22:07'
SELECT cast(convert(varchar(20),substring(convert(nvarchar(20),#date, 9), 0, 21)
+ ' ' + substring(convert(nvarchar(30), #date, 9), 25, 2),105) as datetime)
Your field is a NVARCHAR field so just return it without any conversion. In your query you convert string representation into the DATETIME type and returns it. Your browser software which shows query results convert DateTime value into string representation to show it to you and conversion format depends on this software usually you can change it changing Windows Regional Settings.
You can get AM/PM data using following query
declare #date datetime
select #date= CAST('07/11/2013 11:22:07' AS datetime)
select RIGHT ( CONVERT(VARCHAR,#date,9),2)

Microsoft SQL Server 2008 - Dates

I have a couple of questions in regards to dates in SQL Server.
How do I separate a datetime value "2011-08-10 14:56:17.267" into date and timestamp in two separate columns. Eg. Date "2011-08-10" and timestamp "14:56:17"
I want remove the timestamp from datetime value into "2011-08-10" and still be able to order the data by date (therefore not converted to varchar). Also is there away to change the date value as '10 Aug 2011' and still can sort (not alphabetically but in real date order).
Thank you,
HL
For the first one:
UPDATE atable
SET
DateColumn = CAST(DateTimeColumn AS date),
TimeColumn = CAST(DateTimeColumn AS time)
As for the second one, date display format is something that is unrelated to the date value. You can order the result set by your date column, but in the SELECT clause you can use CONVERT to display the date in the desired format. For example:
SELECT
CONVERT(varchar, DateColumn, 106) AS Date,
…
FROM atable
ORDER BY DateColumn
use CONVERT function with parameters from resource http://www.mssqltips.com/tip.asp?tip=1145
-- simple conversion example:
SELECT CONVERT(VARCHAR(10), GETDATE(), 102) -- for date
SELECT CONVERT(VARCHAR(10), GETDATE(), 8) -- for time