Numeric to datetime conversion in SQL Server 2016 error - sql

This is for SQL Server 2016.
Column
MyDate
---------
20200915
20201007
Unfortunately the data type is numeric(8,0)
I am trying to get date as
2020-09-15 00:00:00
2020-10-07 00:00:00
Code:
convert(varchar, MyDate, 120)
Please suggest
Thanks

You could write this as:
convert(date, convert(varchar(8), mydate))
SQL Server does not allow converting an integer to a date directly, so we need an intermediate casting to a string. If you want a date an time, use datetime instead of date.
If there is a chance that some of your numeric dates might be invalid, you can use try_convert() instead of convert().
Another option is arithmetics and datefromparts() (I doubt that is is more efficient):
datefromparts(mydate / 10000, (mydate % 10000) / 100, mydate % 100)

Related

SQL Server error in conversion of date from string

NPD.CreatedOn is defined as a datetime datatype column (in SQL Server).
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(MONTH, CONVERT(VARCHAR(7), NPD.CreatedOn, 126), CONVERT(VARCHAR(30), GETDATE(), 126)) <= 6
I get this error:
Conversion failed when converting date and/or time from character string.
What can I try to resolve it?
Don't use things like DATEDIFF in the WHERE on your columns, such queries aren't SARGable and thus can (will) perform poorly. If you want rows where the date is on or after the start of the month 6 months ago then do the date logic on GETDATE()/SYSDATETIME()/etc:
SQL Server doesn't have a "start of month" function, but you can use EOMONTH and then add a day:
SELECT *
FROM dbo.NPDMaster NPD
WHERE NPD.CreatedOn >= DATEADD(DAY, 1, EOMONTH(GETDATE(),-7));
You don't need to convert the datetime values to text. DATEDIFF() expects datetime values as second and third argument:
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(month, NPD.CreatedOn, GETDATE()) <= 6
The actual reason for the error (as is explained in the documentation), is that ...DATEDIFF implicitly casts string literals as a datetime2 type.

Convert Numeric to Date in MS SQL

There is already a Datecolumn in Table which is in Numeric DataType(Converted to Int for faster ODBC Transfer), How can i convert that number to Data again?
Example the Values are like
42508
42826
43191
42158
42527
Which are nothing but like
SELECT CONVERT(numeric, getdate())
Query Result
43571
Just want to know how can i convert back that to normal date ?
You may use next conversion:
SELECT CONVERT(date, DATEADD(day, 43570, 0))
which will output:
17/04/2019 00:00:00
In this case SQL Server will use implicit data type conversion, because DATEADD() allows datetime datatype as third parameter and DATEADD() will convert 0 to 1900-01-01.

Convert varchar containing various formats to DATETIME

I have a record_created column of type varchar containing multiple values formatted in two different ways throughout.
2017-04-17 16:55:53.3840460
Sep 18 2015 11:25PM
How can I convert this column into a DATETIME to be compared to GETDATE?
GETDATE() is SQL Server specific if so, then you can use try_convert() :
select cast(try_convert(datetime2, col) as datetime)
from table t
where try_convert(datetime2, col) is not null;
However, if the string date is exactly the same format which you have provide then you can simply do casting :
select cast(cast(col as datetime2) as datetime)
from table t;
If you are using SQL Server, then you may be able to use the CONVERT function here:
SELECT
CONVERT(datetime, LEFT('2017-04-17 16:55:53.3840460', 23), 121) AS date1,
CONVERT(datetime, 'Sep 18 2015 11:25PM', 100) AS date2;
Your first type of timestamp seems to work with mask 121, and the second one works with mask 100. The demo link below shows that the conversions are working.
Demo

Simple DateTime sql query

How do I query DateTime database field within a certain range?
I am using SQL SERVER 2005
Error code below
SELECT *
FROM TABLENAME
WHERE DateTime >= 12/04/2011 12:00:00 AM
AND DateTime <= 25/05/2011 3:53:04 AM
Note that I need to get rows within a certain time range. Example, 10 mins time range.
Currently SQL return with Incorrect syntax near '12'."
You missed single quote sign:
SELECT *
FROM TABLENAME
WHERE DateTime >= '12/04/2011 12:00:00 AM' AND DateTime <= '25/05/2011 3:53:04 AM'
Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.
SELECT *
FROM TABLENAME
WHERE
DateTime >= '2011-04-12T00:00:00.000' AND
DateTime <= '2011-05-25T03:53:04.000'
You need quotes around the string you're trying to pass off as a date, and you can also use BETWEEN here:
SELECT *
FROM TABLENAME
WHERE DateTime BETWEEN '04/12/2011 12:00:00 AM' AND '05/25/2011 3:53:04 AM'
See answer to the following question for examples on how to explicitly convert strings to dates while specifying the format:
Sql Server string to date conversion
This has worked for me in both SQL Server 2005 and 2008:
SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}
You can execute below code
SELECT Time FROM [TableName] where DATEPART(YYYY,[Time])='2018' and DATEPART(MM,[Time])='06' and DATEPART(DD,[Time])='14
SELECT *
FROM TABLENAME
WHERE [DateTime] >= '2011-04-12 12:00:00 AM'
AND [DateTime] <= '2011-05-25 3:35:04 AM'
If this doesn't work, please script out your table and post it here. this will help us get you the correct answer quickly.
select getdate()
O/P
----
2011-05-25 17:29:44.763
select convert(varchar(30),getdate(),131) >= '12/04/2011 12:00:00 AM'
O/P
---
22/06/1432 5:29:44:763PM
Others have already said that date literals in SQL Server require being surrounded with single quotes, but I wanted to add that you can solve your month/day mixup problem two ways (that is, the problem where 25 is seen as the month and 5 the day) :
Use an explicit Convert(datetime, 'datevalue', style) where style is one of the numeric style codes, see Cast and Convert. The style parameter isn't just for converting dates to strings but also for determining how strings are parsed to dates.
Use a region-independent format for dates stored as strings. The one I use is 'yyyymmdd hh:mm:ss', or consider ISO format, yyyy-mm-ddThh:mi:ss.mmm. Based on experimentation, there are NO other language-invariant format string. (Though I think you can include time zone at the end, see the above link).
if you have a type of datetime and you want to check between dates only ,,,use cast to select between two dates ....
example...
... where cast( Datetime as date) >= cast( Datetime as date) AND cast( Datetime as date) <= cast( Datetime as date)

How do you extract just date from datetime in T-Sql?

I am running a select against a datetime column in SQL Server 2005. I can select only the date from this datetime column?
Best way is:
SELECT DATEADD(day, DATEDIFF(Day, 0, #ADate), 0)
This is because internally, SQL Server stores all dates as two integers, of which the first one is the ****number of days*** since 1 Jan 1900. (the second one is the time portion, stored as the number of seconds since Midnight. (seconds for SmallDateTimes, or milleseconds for DateTimes)
Using the above expression is better because it avoids all conversions, directly reading and accessing that first integer in a dates internal representation without having to perform any processing... the two zeroes in the above expression (which represent 1 Jan 1900), are also directly utilized w/o processing or conversion, because they match the SQL server internal representation of the date 1 jan 1900 exactly as presented (as an integer)..
*NOTE. Actually, the number of date boundaries (midnights) you have to cross to get from the one date to the other.
Yes, by using the convert function. For example:
select getdate(), convert(varchar(10),getdate(),120)
RESULTS:
----------------------- ----------
2010-05-21 13:43:23.117 2010-05-21
You can use the functions:
day(date)
month(date)
year(date)
Also the Datepart() function might be of some use:
http://msdn.microsoft.com/en-us/library/ms174420(SQL.90).aspx
DECLARE #dToday DATETIME
SET #dToday = CONVERT(nvarchar(20), GETDATE(), 101)
SELECT #dToday AS Today
This returns today's date at 12:00am : '2010-05-21 00:00:00.000'
Then you can use the #dToday variable in a query as needed
CONVERT (date, GETUTCDATE())
CONVERT (date, GETDATE())
CONVERT (date, '2022-18-01')
I don't know why the others recommend it with varchar(x) tbh.
https://learn.microsoft.com/de-de/sql/t-sql/functions/getdate-transact-sql