Convert varchar column to datetime in sql server - sql

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

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.

Splitting a datetime and replace the year part

I need to split a date like '01/12/15' and replace the year part from 15 to 2015 (ie; 01-12-2015). I get the year by the sql query:
select YEAR('10/12/15')
It returns the year 2015. but I have to replace 15 to 2015. how do i achieve this.
Anyone here please help me. thanks in advance..
Edited:
I've tried following query too..
declare #date varchar='10/12/2015'
declare #datenew date
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
print #datenew
but it throws some error like this :
Conversion failed when converting date and/or time from character string.
How do I change the varchar to date and replace its year part to 4 digit.. please help me..
DECLARE #intFlag INT,#date varchar(150),#payperiod numeric(18,0),#emp_Id varchar(50)
SET #intFlag = 1
declare #count as int set #count=(select count(*) from #myTable)
WHILE (#intFlag <=#count)
BEGIN
select #emp_Id=Employee_Id from #myTable where rownum=#intFlag
select #date=attendance_date from #myTable where rownum=#intFlag
declare #datenew datetime
SELECT #datenew=convert(datetime,CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103) ,103)
It throws the error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
As you said your column is in varchar type, try the following
Query
CREATE TABLE #temp
(
dt VARCHAR(50)
);
INSERT INTO #temp VALUES
('01/12/15'),
('02/12/15'),
('03/12/15'),
('04/12/15'),
('05/12/15');
UPDATE #temp
SET dt = REPLACE(LEFT(dt, LEN(dt) - 2)
+ CAST(YEAR(CAST(dt AS DATE)) AS VARCHAR(4)), '/', '-');
SELECT * FROM #temp;
EDIT
While declaring the variable #date you have not specified the length.
Check the below sql query.
declare #date varchar(10)='10/12/2015'
declare #datenew date
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
print #datenew
The simplest way by casting Date object to VARCHAR
SELECT RIGHT(CAST(YEAR('10/12/15') AS VARCHAR), 2)
If you want to change the format and get the varchar try to use:
SELECT CONVERT(varchar(10), CAST('10/12/15' AS DATETIME), 105)
I hope it helps.
What datatype is the value '01/12/15'?
Maybe this will help you:
SELECT YEAR(CAST('10/12/15' AS DATE))
Problem with your query is that you haven't specified length for varchar datatype:
declare #date varchar(12)='10/12/2015'
declare #datenew date
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
print #datenew
Try using:
Declare #date nvarchar(20)='10/12/15'
Declare #datenew nvarchar(40)
SELECT #datenew=CONVERT(nvarchar(10), CAST(#date AS DATETIME), 103)
Print #datenew

SQL Custom datetime format to datetime

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

Convert datetime and varchar to single date

I have a following database columns and the values
MyDate datetime and My_Time varchar(5)
the values stored are
2006-09-05 00:00:00.000 and 16:47
Now I want to add this two columns and get a single datetime value 2006-09-05 16:47:00.000
How can I do this in SQL ?
UPDATE:
Some rows have NULL values for DocDate and DocTime.
So i am getting error like Conversion failed when converting date and/or time from character string
Simply...
DECLARE #date DATETIME
DECLARE #time VARCHAR(5)
SET #date = '2006-09-05 00:00:00.000'
SET #time = '16:47'
SELECT CAST(#date + #time AS DATETIME) -- 2006-09-05 16:47:00.000
Try this:
select dateadd(ss, datediff(ss, 0, #My_Time), #MyDate)
Key point is to understand that it's the same as...
select dateadd(ss, datediff(ss, 0, cast(#My_Time as time)), #MyDate)
...but the conversion is done explicitly.
EDIT
For default time and/or date, use ISNULL or COALESCE as appropriate.
Example:
SELECT
CAST(
isnull(#date, '2000-1-1') +
isnull(#time, '0:0')
AS DATETIME)
Try
CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME) as CombinedDate

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)