How to select numeric string as a valid DATE - sql

CUSTOMER(ID,NAME,ENTRY_DT)
1,Dave,8312012
2,Tom,11262013
3,Iva,3312012
.
.
.
So the ENTRY_DT column has numeric string value in MDDYYYY or MMDDYYYY format.
I want to write a simple select query so that ENTRY_DT shows
8/31/2012
11/26/2013
3/31/2012
.
.
.

DECLARE #TABLE TABLE (Int_Date INT)
INSERT INTO #TABLE VALUES
(8312012),
(11262013),
(3312012)
SELECT LEFT(RIGHT('00000000'+ CAST(Int_Date AS VARCHAR(10)), 8), 2) +'/'
+REVERSE(SUBSTRING(REVERSE(Int_Date), 5, 2)) + '/' + RIGHT(Int_Date, 4)
FROM #TABLE
Result
08/31/2012
11/26/2013
03/31/2012

Select covert(date,right(('00000000' + entry_dt),8),101)
--- if it is SQL server 2008 or above
Replace date with date time if it is 2005 or below.

select id, name, CONVERT(datetime, entry_dt, 101)

SELECT LEFT(RIGHT('00000000'+CAST(ENTRY_DT AS VARCHAR(10)),8),2)+'/'+REVERSE(SUBSTRING(REVERSE(ENTRY_DT), 5, 2))+'/'+REVERSE(SUBSTRING(REVERSE(ENTRY_DT), 1, 4)) FROM #CUSTOMER

SELECT SUBSTRING(RIGHT('00000000'+ENTRY_DT,8),1,2)+'/'+SUBSTRING(RIGHT('00000000'+ENTRY_DT,8),3,2)+'/'+SUBSTRING(RIGHT('00000000'+ENTRY_DT,8),5,4) FROM #CUSTOMER

Related

Varchar date to datetime sql

I have a varchar date format of 01012018, I need to convert this to a date in a SQL Server view:
CONVERT(VARCHAR(50), CONVERT(DATE, [Date], 103), 103)
I have tried the above with no joy.
Please help
SQL Server can be a bit cumbersome when parsing dates that are not one of the "built-in" ones. You can use parse()/try_parse(), but that is a relatively new function.
In your case, it is pretty simple to construct the date value directly:
select convert(date, concat(right(ddmmyyyy, 4), substring(ddmmyyyy, 3, 2), left(ddmmyyyy, 2)))
from (values ('01012018')) v(ddmmyyyy)
There is no style ddMMyyyy in the CONVERT Date and Time Styles, but there is a dd/MM/yyyy, so you could inject these characters in and convert:
SELECT TRY_CONVERT(date, STUFF(STUFF(v.ddmmyyyy, 5, 0, '/'), 3, 0, '/'), 103)
FROM (VALUES ('01012018')) v (ddmmyyyy);
I've also used TRY_CONVERT incase you have some other "bad" values (perhaps '01312019'). These will return NULL when the varchar represents an invalid date.
Use CONVERT() as
DECLARE #Var VARCHAR(10) = '01012018'
SELECT CONVERT(DATE,
CONCAT( RIGHT(#Var, 4),
SUBSTRING(#Var, 3, 2),
LEFT(#Var, 2)
)
)
Demo
Finally, I would recommend ALTERing your table (which is the right solution) and change the data type of your column to DATE data type.
CREATE TABLE T(
MyCol VARCHAR(10)
);
INSERT INTO T(MyCol) VALUES
('01012018'),
('01022018'),
('01032018'),
('WrongData');
SELECT MyCol
FROM T;
UPDATE T
SET MyCol = TRY_CONVERT(DATE,
CONCAT( RIGHT(MyCol, 4),
SUBSTRING(MyCol, 3, 2),
LEFT(MyCol, 2)
)
);
ALTER TABLE T
ALTER COLUMN MyCol DATE;
SELECT MyCol
FROM T;
Second Demo

SQL Query : How to get date reference of Month And Year Column?

I need a help to change the Month & Year column as Date in Result.
Ex :
Table Name : AA
Month Year
4 2016
5 2015
Result Should Be:
01-04-2016
01-05-2015
I need a SQL query for this? Can any one help me out?
Try like this,
DECLARE #AA TABLE (
Month INT
,Year INT
)
INSERT INTO #AA (
Month
,Year
)
VALUES (
4
,2016
)
,(
5
,2015
)
SELECT convert(DATE, convert(VARCHAR(50), year * 10000 + month * 100 + 01)) AS DATE
FROM #AA
Try this code:
select '01-'+cast([month] as nvarchar) + '-'+cast([Year] as nvarchar)
from YourTable
Assuming int data types:
DECLARE #Month int = 4, #Year int = 2016
SELECT CAST(CAST(#Year * 10000 + #Month * 100 + 01 As char(8)) as date)
Assuming char/varchar data types:
DECLARE #MonthString varchar(2) = 4, #YearString char(4) = 2016
SELECT CAST(#YearString +'-'+ RIGHT('00' + #MonthString, 2) + '-01' as date)
Results in both cases:
2016-04-01 -- (Date data type)
Add square brackets for the reserve keywords:
DECLARE #AA TABLE ([Month] INT, [Year] INT);
INSERT INTO #AA ([Month], [Year]) VALUES
(4, 2016),
(5, 2015);
SELECT '01-' + RIGHT('00' + CAST([MONTH] AS VARCHAR), 2) + '-' + CAST([Year] AS VARCHAR)
FROM #AA
Result:
01-04-2016
01-05-2015
DECLARE #Table1 TABLE
(Month int, Year int)
;
INSERT INTO #Table1
(Month, Year)
VALUES
(4, 2016),
(5, 2015)
;
select '01'+'-'+RIGHT('000'+CAST(Month AS VARCHAR(3)),2)+'-'+CAST(Year AS VARCHAR) from #Table1
Do not do varchar convertions. Use like below
declare #t table([Month] int,[Year] int)
insert into #t
select 4, 2016 union all
select 5, 2015
select dateadd(month,month-1,dateadd(year,[year]-1900,0)) from #t
You can use concat function to acieve this
SELECT CONCAT('01-',year,'-',month) as req_date from tableName
try this:
declare #y varchar(4)='2015'
declare #m varchar(2)='5'
--try_prase is available starting sql 2012
print try_parse('01-'+#m+'-'+#y as datetime using 'en-us')
print convert(datetime,'01-'+#m+'-'+#y,121)

Convert varchar MMDDYYYY to MM/DD/YYYY datetime and select the most recent date only

Okay, so I have kind of a weird issue... the dates in the table have been entered in as string values MMDDYYYY and I'm trying to have the displayed as MM/DD/YYYY in a report and only select the most recent date pertaining to an ID, because some ID's may have multiple dates.
Example of my table:
ID | MyDate |
------+----------+
1 | 01302014 |
1 | 04222014 |
2 | 01302014 |
What I want to see when I select and insert into a temp table is this:
ID | MyDate |
------+-----------+
1 | 4/22/2014 |
2 | 1/30/2014 |
I know that storing dates as string values is a poor practice especially when storing them as MMDDYYYY, but does anyone have a solution to this nightmare?
EDIT
I forgot to mention that some fields might be NULL. Not sure if that makes a difference or not, but I think it does if I try to flip the dates using Right, Left, Convert.
This question is for almost a year ago, nut probably someone can find it useful.
You need to CONVERT your string to DATE format and use a ROW_NUMBER function to window your result set.
Create table
DECLARE #tbl TABLE(Id INT, myDate VARCHAR(8))
Sample data
INSERT #tbl
SELECT 1 , '01302014' UNION ALL
SELECT 1 , '04222014' UNION ALL
SELECT 2 , '01302014'
Query
;WITH C AS(
SELECT ROW_NUMBER() OVER (PARTITION BY Id ORDER BY CONVERT(DATETIME, (SUBSTRING(myDate, 5, 4) + '.' + SUBSTRING(myDate, 1, 2) + '.' + SUBSTRING(myDate, 3, 2)), 101) DESC) AS Rn
,Id
,CAST(CONVERT(DATETIME, (SUBSTRING(myDate, 5, 4) + '.' + SUBSTRING(myDate, 1, 2) + '.' + SUBSTRING(myDate, 3, 2)), 101) AS DATE) AS myDate
FROM #tbl
)
SELECT Id, myDate
FROM C
WHERE Rn = 1
SQLFiddle Demo
Using a CONVERT like the following code snippet will work on any SQL Server regardless of language and/or locale configuration.
DECLARE #OldDate varchar(8);
SELECT #OldDate = '04252012';
SELECT CONVERT(datetime, substring(#OldDate,5,4) + '-' + substring(#OldDate,1,2) + '-' + substring(#OldDate,3,2) + 'T00:00:00')
You could try this:
convert(date,SUBSTRING (MyDate,1,2)+'/'+SUBSTRING (MyDate,3,2)+'/'+SUBSTRING (MyDate,5,4),101)
Select CONVERT(datetime,RIGHT('01302014',4) +
LEFT('01302014',2) +
SUBSTRING('01302014',3,2))
'2014-01-30 00:00:00.000'
;with Cte as (Select Id,CONVERT(datetime,RIGHT(MyDate,4)+LEFT(MyDate,2)+SUBSTRING(MyDate,3,2)) as sDate, C=ROW_NUMBER()
over(PARTITION By Id Order by MyDate desc)
From #Temp)
select *
from Cte
where C=1
First do a conversion to a datetime datatype, then convert it to a format you wish to:
select id, convert(varchar, max(convert(datetime,right(mydate, 4)+left(mydate,4))), 101)
from #t
group by id
Although I can't understand why would it not suffice to just convert it do datetime and leave the formatting where it belongs, to the client.
Select id,convert(varchar(11),cast(dateValue as Date),101)
From
(
Select id,MAX(cast(MyDate As Date)) as dateValue
From tableName
Group By id
) t
The simplest solution is mySQL str_to_date() function.
STR_TO_DATE(`MyDate`, '%m%d%Y')
This will convert it to a DATETIME which you then format as required
DATE_FORMAT(STR_TO_DATE(`MyDate`, '%m%d%Y'), '%c/%e/%Y')
Complete Query:
Select ID, Case When IsDate(RIGHT(MyDate,4)+LEFT(MyDate,2)+SUBSTRING(MyDate,3,2)) = 1
THEN Convert(varchar(10), Convert(datetime, RIGHT(MyDate,4)+LEFT(MyDate,2)+SUBSTRING(MyDate,3,2)), 101)
ELSE Null END AS MyDate FROM YourTable a where Case When IsDate(RIGHT(MyDate,4)+LEFT(MyDate,2)+SUBSTRING(MyDate,3,2)) = 1
THEN Convert(varchar(10), Convert(datetime, RIGHT(MyDate,4)+LEFT(MyDate,2)+SUBSTRING(MyDate,3,2)), 101)
ELSE Null END = (Select Max(Case When IsDate(RIGHT(MyDate,4)+LEFT(MyDate,2)+SUBSTRING(MyDate,3,2)) = 1
THEN Convert(varchar(10), Convert(datetime, RIGHT(MyDate,4)+LEFT(MyDate,2)+SUBSTRING(MyDate,3,2)), 101)
ELSE Null END)
FROM YourTable b
Where a.ID = b.ID
)
This is a modified version from Dimitris Kalaitzis' answer.
First, you will need to convert your MyDate into String. The data for example (01302014) is not treated as a string and the leading zero will be removed when you convert it. Therefore, use CAST to make MyDate as a String and add a leading 0 to it. Then you find the right 8 characters so to get rid of the leading zero for months from Oct to Dec.
Here is the code that should work for you:
CONVERT(Date, SUBSTRING(RIGHT('0' + CAST(MyDate AS VARCHAR(10)), 8), 1, 2) + '/' + SUBSTRING(RIGHT('0' + CAST(MyDate AS VARCHAR(10)), 8), 3, 2) + '/' + SUBSTRING(RIGHT('0' + CAST(MyDate AS VARCHAR(10)), 8), 5, 4), 101)
Hope this helps.
You first have to add the slashes to be able to convert it to a date, use STUFF
Then convert it to a DATE and select the MAX group by ID
Query:
SELECT ID, FORMAT(MAX(CONVERT(DATE,STUFF(STUFF(MyDate,3,0,'/'),6,0,'/'))),'MM/dd/yyyy') AS MyDate FROM TableName
GROUP BY ID

combine 2 varchar column's data and convert to datetime

I have 2 columns in a table of varchar datatype.
date and type are the column names in table.
the data present in the table looks like this
date time
20090610 132713
20090610 132734
i need ms sql server query to concatenate these 2 columns data and display as datetime format.
Note :
1. the datatype of those 2 columns cannot be changed now.
2. i tried
select convert(datetime,date + time)
it says "Conversion failed when converting date and/or time from character string."
Suggest the possible solution.
This will return a datetime. The bottom line is to be replaced by your table
select convert(datetime,date,112)+
coalesce(stuff(stuff(rtrim(time), 5,0,':'), 3,0,':'), '') newdate
from
(VALUES ('20090610','132713'),('20090610', '132734'),('20090610', ' ')) yourtable(date,time)
Result:
newdate
2009-06-10 13:27:13.000
2009-06-10 13:27:34.000
2009-06-10 00:00:00.000
You can get it using
SELECT
convert(varchar, convert(datetime, date), 111)
+ ' ' + substring(time, 1, 2)
+ ':' + substring(time, 3, 2)
+ ':' + substring(time, 5, 2)
CREATE TABLE #Table
(
[date] VARCHAR(100),
[time] VARCHAR(100)
)
INSERT INTO #Table VALUES
('20090610','132713'),
('20090610','132734')
;WITH Bits_CTE
AS
(
SELECT
[Date],
[Time],
[hrs] = CONVERT(INT,SUBSTRING([Time], 1, 2)),
[mns] = CONVERT(INT,SUBSTRING([Time], 3, 2)),
[secs] = CONVERT(INT,SUBSTRING([Time], 5, 2))
FROM #Table
)
SELECT
[Date],
[Time],
DATEADD(HOUR,[hrs],
DATEADD(MINUTE,[mns],
DATEADD(SECOND,[secs],[Date])))
FROM Bits_CTE
CREATE FUNCTION [dbo].[DateTimeAdd]
(
#datepart date,
#timepart time
)
RETURNS datetime2
AS
BEGIN
RETURN DATEADD(dd, DATEDIFF(dd, 0, #datepart), CAST(#timepart AS datetime2));
END
Sorry - Missed the bit in your question about storing the date and time as varchars. You would therefore still need to convert these data itemsbefore using this function.

SQL Server: Date conversion problem?

I have a column which has date-values stored in varchar (format ddmmyy) like this
231280
121280
131185
...
How to convert these values into datetime data type?
Set DateFormat DMY
GO
Select Cast(Stuff(Stuff(SomeValue, 3, 0, '-'), 6, 0, '-') As datetime)
From MyData
Use substring to get year, month, and day, if year greater than 11 add 19 to it if not add 20, to get year in format 2009, but this is your query just instead of string add your column name
select CAST(
CASE WHEN CAST(SUBSTRING('231280', 5, 2) AS INT) >11
THEN '19'+SUBSTRING('231280', 5, 2)
else '20'+SUBSTRING('231280', 5, 2)
END
+'-'+SUBSTRING('231280', 3, 2)+'-'+SUBSTRING('231280', 1, 2) as datetime)
You'd have to use some substring footwork to convert your string to a known date format. Here's an example converting the string to format 3, "British/French":
declare #YourTable table (YourColumn varchar(50))
insert #YourTable
select '231280'
union all select '121280'
union all select '131185'
select convert(datetime, substring(YourColumn,1,2) + '/' +
substring(YourColumn,3,2) + '/' + substring(YourColumn,5,2), 3)
from #YourTable
Because this format is non standard, use
DECLARE #field char(6)
SET #field = '231280'
select convert(datetime, right(#field, 2) + substring(#field, 3, 2) + left(#field, 2) , 12)