SQL Custom datetime format to datetime - sql

I have a varchar which is coming through as the following format: yyyy-dd-MM hh:mm:ss
I need to be able to convert that to a valid datetime, what will be the best method?
Edit for example:
DECLARE #d varchar = '2014-17-01 12:00:00'
SELECT CONVERT(DATETIME, #d, 103);
returns
Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.

Via CONVERT?
SELECT CONVERT(DATETIME, '2014-31-01 17:00:00', 103 /* British */);
(No column name)
2014-01-31 17:00:00.000

You can use CONVERT as:
DECLARE #TodayDate datetime
SET #TodayDate = GETDATE()
SELECT CONVERT(VARCHAR, #TodayDate, 110) AS TodayDate
Output:
07-04-2014
Hope it helps !

EDITED to add SET DATEFORMAT. This resolved the error for me and ensures everything gets into the correct bucket.
SET DATEFORMAT ydm
DECLARE #d VARCHAR(20) = '2014-17-01 12:00:00';
DECLARE #targetDate DATETIME = GETDATE(); -- Control Date
DECLARE #passedDate DATETIME = CAST(#d AS DATETIME);
SELECT #targetDate, #passedDate;

Try to interchange day and month and then PARSE new string to datetime.
DECLARE #d varchar(50) = '2014-17-01 12:00:00'
DECLARE #year varchar(10) = SUBSTRING(#d,1,4)
DECLARE #day varchar(10) = SUBSTRING(#d,6,2)
DECLARE #month varchar(10) = SUBSTRING(#d,9,2)
DECLARE #time varchar(10) = SUBSTRING(#d,12,8)
DECLARE #new_d varchar(50) = #year+'-'+#month+'-'+#day+' '+#time
SELECT PARSE(#new_d AS datetime USING 'en-US') as Result

Related

SQL Select statement, change Format mmddyy to dd-mon-yyyy with convert

I want to select field opendate mmddyy data type decimal(6,0) to dd-mon-yyyy. How do I modify this statement?
select convert(varchar(10),M.opendate, 106)
FROM All.Customer M
The above results in the following error:
[SQL0204] CONVERT in *LIBL type *N not found
You can try this:
DECLARE #InputDate VARCHAR(8)
SET #InputDate = '073019'
DECLARE #InputYear VARCHAR(4)
DECLARE #InputMonth VARCHAR(2)
DECLARE #InputDay VARCHAR(2)
SET #InputYear = '20' + SUBSTRING(#InputDate, 5, 2)
SET #InputMonth = LEFT(#InputDate, 2)
SET #InputDay = SUBSTRING(#InputDate, 3, 2)
DECLARE #OutputDate DATE
SET #OutputDate = #InputYear +'-'+ #InputMonth +'-'+ #InputDay
SELECT CONVERT(VARCHAR(15), #OutputDate, 106)
Still you should know how to define the first 2 digits of the year. I have used '20' as default.

Conversion failed when converting date and/or time from character string in sql server

I have a function to convert a string to datetime (101) format.
But it gives me an error when I convert this value.
2016-03-01 00:00:00.0000000
And the error is
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.
And my function is ..
ALTER FUNCTION [dbo].[ConvertToDate]
(
#Value nVarchar(MAX)
)
RETURNS DATETIME
AS
BEGIN
IF (#Value <> NULL OR #Value <> '')
BEGIN
DECLARE #dt DATETIME
SET #dt = CONVERT(DATETIME,#Value,101)
--SET #dt = CAST(#Value AS DATETIME(101))
RETURN #dt
END
RETURN NULL
END
What is the problem?
It is problem your data. It is not converting.
Your data should be like this
'2016-03-01 00:00:00.0000000'
But you can change your data like this
'2016-03-01 00:00:00.000'
Too many zeros in the millisecond part. This works fine
DECLARE #Value nVarchar(MAX)='2016-03-01 00:00:00.000'
SELECT CONVERT(DATETIME,#Value,101)
You can try using LEFT like this
DECLARE #Value nVarchar(MAX)='2016-03-01 00:00:00.000000'
SELECT CONVERT(DATETIME,LEFT(#Value,23),101)
DECLARE #dt VARCHAR(50) ='2016-03-01 00:00:00.000000'
select CAST (#dt AS DATETIME2)

Convert varchar column to datetime in sql server

I have a table with following definition and data.
Definition:
CREATE TABLE [dbo].[TestTB]
(
[CREATEDATE] [nvarchar](50) NULL
) ON [PRIMARY]
Data:
10/9/2014
1/26/2015
2/16/2015
When I run the query:
Select
CAST(CREATEDATE AS DATETIME) as CREATEDATE
FROM
[dbo].[TestTB]
It is throwing error:
Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.
The above does not work even after running
SET DATEFORMAT dmy
However the following query works fine
DECLARE #data nvarchar(50)
SET #data = ' 10/9/2014 '
Select CAST(#data as DateTime)
Above query returns: 2014-10-09 00:00:00.000
How do I convert a date string (of mm/dd/yyyy format) stored in a column to datetime?
First, if your table column is "DateTime" type than it will save data in this format "2014-10-09 00:00:00.000" no matter you convert it to date or not. But if not so and if you have SQL Server version 2008 or above than you can use this,
DECLARE #data nvarchar(50)
SET #data = '10/9/2014'
IF(ISDATE(#data)>0)
BEGIN
SELECT CONVERT(DATE, #data)
END
Otherwise
DECLARE #data nvarchar(50)
SET #data = '10/9/2014'
IF(ISDATE(#data)>0)
BEGIN
SELECT CONVERT(DATETIME, #data)
END
To Insert into table
INSERT INTO dbo.YourTable
SELECT CREATEDATE FROM
(
SELECT
(CASE WHEN (ISDATE(#data) > 0) THEN CONVERT(DATE, CREATEDATE)
ELSE CONVERT(DATE, '01/01/1900') END) as CREATEDATE
FROM
[dbo].[TestTB]
) AS Temp
WHERE
CREATEDATE <> CONVERT(DATE, '01/01/1900')
DECLARE #data nvarchar(50)
SET #data = ' 10/9/2014 '
SELECT CONVERT(datetime, #data, 101)
SELECT CONVERT(datetime, CREATEDATE, 101) as CREATEDATE
FROM [dbo].[TestTB]
http://www.sqlfiddle.com/#!6/f2103
please check this http://msdn.microsoft.com/en-us/library/aa226054%28SQL.80%29.aspx
Try this out:
SELECT IIF(ISDATE(CREATEDATE) = 1, CONVERT(DATETIME, CREATEDATE, 110), CREATEDATE) as DT_CreateDate
FROM [dbo].[TestTB]
SQL Fiddle Solution
nvarchar to datetime is an implicit conversion, it means you can do this:
declare #strDate nvarchar(50), #myDate datetime
set #strDate = '01/26/2013'
set #myDate = #strDate
But your problem is date format so you have to convert it, but you have to scpecify the format or style and the code of the style you're using is 101 (according to this table) so the secure way:
declare #strDate nvarchar(50), #myDate datetime
set #strDate = '01/26/2013'
set #myDate = CONVERT(DATETIME, #strDate, 101)
You can skip the code but with diferent configuration(server) that code will break.
If you use the ISO style (yyyymmdd) you never would'nt have to worry and the conversion would be implicit:
declare #strDate nvarchar(50), #myDate datetime
set #strDate = '20150421' --ISO style (yyyymmdd)
set #myDate = #strDate

Error when running SQL stored procedure coversion failed when converting date and/or time from character string

DECLARE #i varchar(13)
DECLARE #Year varchar(30)
SET #i = 2
SET #Year = 2013
SELECT SUM(CAST([totalAfterMultiplier] as money)) as 'totalAfterMultiplier' FROM [postfinanceAfterMultiplier]
WHERE CAST([ORDER] as date) >= '01/'+#i+'/'+ #Year +'' AND CAST([ORDER] as date) <= '31/'+#i+'/'+ #Year +''
I am getting this error: Conversion failed when converting date and/or time from character string.
All values in the database are varchar(50)
I have looked at the other posts and can't seem to get it working
Thank you all for your help
Don't store dates as varchar.
if you want to convert to date from string 'dd/mm/yyyy', use explicit format 103, like select convert(date, '01/12/2013', 103). See other formats here - CAST and CONVERT (Transact-SQL)
I found that the following solution works:
DECLARE #i varchar(13)
DECLARE #Year varchar(30)
SET #i = 2
SET #Year = 2013
SELECT SUM(CAST([totalAfterMultiplier] as money)) as 'totalAfterMultiplier' FROM [postfinanceAfterMultiplier]
WHERE MONTH([ORDER]) = #i AND YEAR([ORDER]) = #Year

why doesn't date show am or pm

Why am I not getting time with am or pm
DECLARE #inputDate varchar(25)
SELECT #inputDate = '3/13/2012 13:00'
-- Declare the return variable here
DECLARE #Result DATETIME
DECLARE #toReturn NVARCHAR(25)
-- Add the T-SQL statements to compute the return value here
SET #inputDate = REPLACE(#inputDate, '24:00', '00:00')
SET #Result = null
SET #toReturn = null
IF (ISDATE(#inputDate)=1)
BEGIN
DECLARE #utcOffset int
SET #utcOffset = -(DATEDIFF(HH, GETUTCDATE(), GETDATE()))
SET #Result = DATEADD(HH, #utcOffset, #inputDate)
SET #toReturn = CONVERT(NVARCHAR, #Result, 101)
END
-- Return the result of the function
SELECT #toReturn
Returns only date portion?
You will need to change CONVERT(NVARCHAR, #Result, 101) to something else. 101 returns a mm/dd/yyyy format. See here for more details: http://msdn.microsoft.com/en-us/library/ms187928.aspx
You are using 101 in your last convert statement and that is date only.
Have a look here for other options. CAST and CONVERT (Transact-SQL)
Try another date format instead of 101 in CONVERT operator.
Because your final conversion uses a format that only includes dates - no time component.
Try the following, instead:
SET #toReturn = CONVERT(NVARCHAR, #Result, 121)