Convert varchar value to date in SQL Server - sql-server

I'm converting varchar data to date in SQL server.
Table having data like below,
So it can have NULL value, proper formatted date and can have like 19900411and 04221995.
So I have tried something like below, but getting error.
SELECT CASE
WHEN ISNULL(CAST(Dob AS VARCHAR), '') = '' THEN NULL
WHEN LEN(CAST(Dob AS VARCHAR)) = '8' THEN CONVERT(
VARCHAR(10),
CONVERT(date, RIGHT(Dob, 4) + LEFT(Dob, 2) + SUBSTRING(Dob, 3, 2)),
103
)
ELSE CONVERT(VARCHAR, CAST(Dob AS CHAR(8)), 103)
END
FROM TableName
WHERE Dob IS NOT NULL
Msg 241, Level 16, State 1, Line 3 Conversion failed when converting
date and/or time from character string.
I wanted to get output as date format MM-dd-yyyy
Please help me! Thanks!

Can you check this answer. This is work for Sqlserver 2012 and above.
Based on your discussion I created a sample data.
CREATE TABLE #A
( COL VARCHAR(10)
)
INSERT INTO #A VALUES( NULL),('19900411'),('19900411'),('04-04-1976'),('10-30-1952')
insert into #A values ('04221995')
insert into #A values ('02222009 ')
select * from #a
SELECT
case isdate(col ) when 1 then CONVERT(VARCHAR, CONVERT(DATE, COL) , 105)
when 0 then SUBSTRING(COL,1,2) + '-'+SUBSTRING(COL,3,2) + '-'+SUBSTRING(COL,5,4)
end
FROM #A

You can use this query for your problem. It simply convert your varchar column to formatted MM-dd-yyyy
select convert(varchar(10), cast('2011-09-28' as date), 101)

I think, you need this:
SELECT CASE
WHEN ISNULL(CAST(Dob AS VARCHAR), '') = '' THEN NULL
WHEN LEN(CAST(Dob AS VARCHAR)) = '8' THEN CONVERT(VARCHAR(10),
CONVERT(date, RIGHT(Dob, 2) + '-' + SUBSTRING(Dob, 5, 2) +'-' + LEFT(Dob, 4)),
103)
ELSE CONVERT(VARCHAR, CAST(Dob AS CHAR(10)), 103)
END
FROM tbl
WHERE Dob IS NOT NULL
OUTPUT: 04/11/1990
SQL Fiddle DEMO: SQL DEMO

CREATE TABLE #A
( COL VARCHAR(10)
)
INSERT INTO #A VALUES( NULL),('19900411'),('19900411'),('04-04-1976'),('10-30-1952'),('19950422')
SELECT DATESTRINGFIELD = CONVERT(VARCHAR, CONVERT(DATE, COL) , 101) FROM #A
output
04/11/1990
04/11/1990
04/04/1976
10/30/1952
04/22/1995

Related

SQL Server - convert short date in from old database

I have old DBF database that contains date in old 6 digit formats like 291292 or 150793 or even 010302.
I import tables into SQL Server and now I need to convert it to datetime format.
Of course must be converted to similar strings 29.12.1992, 15.07.1993, 01.03.2002 first.
You may try this.
GO
declare #date date
set #date = '901124'
select CONVERT(varchar(10), #date, 102) as [Date] --- for yyyy.MM.dd format
TRY THIS
declare #dd varchar(10)
set #dd = '201292'
select CONVERT(VARCHAR(10), #dd, 2), CONVERT(VARCHAR(10), GETDATE(), 2)
, (SUBSTRING(#dd, 5,2) + SUBSTRING(#dd, 3,2) + SUBSTRING(#dd, 1,2))
, CONVERT(varchar(10), cast((SUBSTRING(#dd, 5,2) + SUBSTRING(#dd, 3,2) + SUBSTRING(#dd, 1,2)) as DATE) , 102)
Ok it pretty simple:
GO
declare #date varchar(6)
set #date = '241190'
select CONVERT(date, concat(SUBSTRING(#date, 5,2),SUBSTRING(#date, 3,2),SUBSTRING(#date, 1,2)), 101) as [Date]
result is 1990-11-24
declare #date date = '901124'
select CONVERT(date, #date) as [Date]

How to convert datetime string without delimiters in SQL Server as datetime?

I am looking to convert a string like this: 20160520191959550 - that is actually date-time for 2016-05-20 19:19:59.
I tried using CAST as datetime in a SQL statement, but got this error:
Conversion failed when converting date and/or time from character string.
Here is the SQL:
Select Cast(vbon.DATE_INS As datetime) As DINS
From vbon
I routinely use CAST on date strings without delimiters and am looking for a similar solution. Is there a simple way to get the job done without reverting to LEFT, RIGHT and SUBSTRING?
Addtional variant to already posted:
SELECT CONVERT(DATETIME, FORMAT(CONVERT(BIGINT, '20160520191959550'),
'####-##-## ##:##:##"."###'))
In SQL Server 2012 and later, you can use DATETIMEFROMPARTS:
DECLARE #DateTimeString varchar(19) = '20160520191959550';
SELECT DATETIMEFROMPARTS(
SUBSTRING(#DateTimeString,1,4)
, SUBSTRING(#DateTimeString,5,2)
, SUBSTRING(#DateTimeString,7,2)
, SUBSTRING(#DateTimeString,9,2)
, SUBSTRING(#DateTimeString,11,2)
, SUBSTRING(#DateTimeString,13,2)
, SUBSTRING(#DateTimeString,15,3)
);
In earlier versions, one method is to build a ISO 8601 formatted string and use CAST or CONVERT:
SELECT CAST(
SUBSTRING(#DateTimeString,1,4)
+ '-' + SUBSTRING(#DateTimeString,5,2)
+ '-' + SUBSTRING(#DateTimeString,7,2)
+ 'T' + SUBSTRING(#DateTimeString,9,2)
+ ':' + SUBSTRING(#DateTimeString,11,2)
+ ':' + SUBSTRING(#DateTimeString,13,2)
+ '.' + SUBSTRING(#DateTimeString,15,3)
AS datetime2(3));
SELECT CAST(
STUFF(
STUFF(
STUFF(
STUFF('20160520191959550', 9, 0, ' ')
, 12, 0, ':')
, 15, 0, ':')
, 18, 0, '.') AS DATETIME)
I suggest you to create function:
CREATE FUNCTION dbo.datestringtodatetime
(
-- Add the parameters for the function here
#d NVARCHAR(max)
)
RETURNS datetime
AS
BEGIN
-- Declare the return variable here
DECLARE #table TABLE (
id int,
[pos] int,
[sym] char(1)
)
DECLARE #output datetime
--In this table we determine were to put delimeters
INSERT INTO #table VALUES
(1, 5,'-'),
(2, 8,'-'),
(3, 11,'T'),
(4, 14,':'),
(5, 17,':'),
(6, 20,'.')
;WITH cte AS (
SELECT STUFF(#d,t.[pos],0,t.[sym]) as d_, 1 as l
FROM #table t
WHERE t.id = 1
UNION ALL
SELECT STUFF(c1.d_,t.[pos],0,t.[sym]), l+1
FROM cte c1
INNER JOIN #table t
ON t.id = l+1
)
SELECT #output = TRY_CAST(d_ as datetime)
FROM cte
WHERE l = 6
-- Return the result of the function
RETURN #output
END
GO
You can call it like:
SELECT [dbo].[datestringtodatetime] ('20160520191959550')
Output:
2016-05-20 19:19:59.550
If you pass it wrong value you will get NULL
I think convert would work for you. I can't test right now but I have done what you are looking for with dates. Here is a good article:
http://www.sqlusa.com/bestpractices/datetimeconversion/
You can try this:
SELECT CONVERT(VARCHAR(8), vbon.DATE_INS, 112) + REPLACE(CONVERT(varchar, vbon.DATE_INS, 108), ':','')
Ref: Convert DateTime to yyyyMMddHHmm in T-SQL

Update Final SQL Table with Temp Table using select max for Column

Good day all! What I want to do is update FinalTable with a temp table, where the DateStamp Column of The temp table is greater then DateStamp column in the FinalTable
So far I have come up with something like this:
INSERT INTO [dbo].[FinalTable]([DateStamp], [TIME], [DATE], [USER_LOGIN],[USER_NAME], [MODEL_NAME], [SCORECARD_IDENTIFIER], [SCORECARD_NAME],[ELEMENT_IDENTIFIER], [ELEMENT_NAME], [SERIES_IDENTIFIER], [SERIES_NAME],[PERIOD_NAME], [ACTION_TYPE], [ACTION], [PREVIOUS_VALUE], [VALUE], [UNIT])
SELECT
CONVERT(VARCHAR, CONCAT([DATE], ' ' ,[TIME]), 121) AS [DateStamp],
[TIME], [DATE], [USER_LOGIN], [USER_NAME],
[MODEL_NAME], [SCORECARD_IDENTIFIER], [SCORECARD_NAME],
[ELEMENT_IDENTIFIER], [ELEMENT_NAME],
[SERIES_IDENTIFIER], [SERIES_NAME],
[PERIOD_NAME], [ACTION_TYPE], [ACTION],
[PREVIOUS_VALUE], [VALUE], [UNIT]
FROM
#TEMP
WHERE
(SELECT CONVERT(VARCHAR, CONCAT([DATE], ' ' ,[TIME]), 121) AS [DateStamp] FROM #TEMP) > (SELECT MAX([DateStamp]) FROM [Test].[dbo].[FinalTable])
DROP TABLE #TEMP
Unfortunately it gives me an error like this:
Msg 512, Level 16, State 1, Line 17
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The [DateStamp] column in the temp is being created in the select because I am reading a text file. So initially I want to check the two tables and where the [DateStamp] column value is higher in #Temp then the one in the [FinalTable] just add/insert the new rows into [FinalTable]
If anyone suggests something else do let me know. I'm still a newbie to SQL but I'm trying what I can.
Try this
INSERT INTO [dbo].[FinalTable]([DateStamp],[TIME],[DATE]..)
SELECT convert(varchar,CONCAT([DATE], ' ' ,[TIME]), 121) AS [DateStamp],[TIME],[DATE]
FROM #TEMP T
where convert(varchar,CONCAT(T.[DATE], ' ' ,T.[TIME]), 121) > (Select MAX([DateStamp]) FROM [Test].[dbo].[FinalTable])
Also I do not recommend using varchar while comparing dates
Problem here:
where (SELECT convert(varchar,CONCAT([DATE], ' ' ,[TIME]), 121) AS [DateStamp] FROM #TEMP)
Here is no condition on #TEMP

Obtain below date format in SQL server

Please suggest how to format date into this format '05/23/2014 09:56:07 AM' in SQL server.
Is there a style code to be passed to CONVERT function ?
From Sql Server 2012 onwards you can use following query:-
SELECT FORMAT(GETDATE(), 'G');
Otherwise convert function is used to coverts the date into desired fpormat.
try this
select convert(varchar(50), getdate(), 131)
for detail please read http://msdn.microsoft.com/en-us/library/ms187928.aspx
Check this
declare #d datetime = getdate()
select
#d,
CONVERT ( varchar(30), #d, 101 ) ,
convert( varchar(12), #d, 101) + stuff( right( convert( varchar(26),#d, 109 ), 15 ), 7, 7, ' ' ) as formatedDate

Convert date in text format to datetime format in T-SQL

I have a client supplied file that is loaded in to our SQL Server database. This file contains text based date values i.e. (05102010) and I need to read them from a db column and convert them to a normal date time value = '2010-05-10 00:00:00.000' as part of a clean-up process.
Any guidance would be greatly appreciated.
one way by using
CONVERT(datetime,RIGHT(Column,4) + left(Column,4))
example
declare #s char(8)
select #s = '05102010'
select CONVERT(datetime,RIGHT(#s,4) + left(#s,4))
Try:
SELECT
CONVERT(datetime, RIGHT(YourColumn,4)
+LEFT(YourColumn,4)
) AS ProperDateTime
FROM...
working example:
DECLARE #YourTable table (StringDate char(8))
INSERT #YourTable VALUES ('05102010')
INSERT #YourTable VALUES ('03182010')
SELECT
CONVERT(datetime, RIGHT(StringDate,4)
+LEFT(StringDate,4)
) AS ProperDateTime
FROM #YourTable
OUTPUT:
ProperDateTime
-----------------------
2010-05-10 00:00:00.000
2010-03-18 00:00:00.000
(2 row(s) affected)
Quick and dirty:
SELECT
CONVERT(DATETIME,
SUBSTRING(col, 1, 2)
+ '/' + SUBSTRING(col, 3, 2)
+ '/' + SUBSTRING(col, 5, 4))

Resources