sql convert string to date/datetime - sql

My Filename column looks like 'D181115.T000000'. I used the following code to make it a string, looks like '2018-11-15'.
select '20' + substring(filename, 2,2) + '-' + substring(filename, 4,2) + '-' + substring(filename,6,2)
from table_name
Then I want to convert the string to date type (because I need to sort by date)
select convert(datetime, '20 + substring(filename, 2,2) + '-' + substring(filename, 4,2) + '-' + substring(filename,6,2)')
from table_name
Then I got this error message:
The data types varchar and varchar are incompatible in the subtract
operator.
Any help will be greatly appreciated!

I suspet the database is SQL Server. In that case one can use just
select cast('20' + substring('D181115.T000000', 2,6) as date)
or
select try_cast('20' + substring('D181115.T000000', 2,6) as date)
YYYYMMDD is one of the two unambiguous date formats. The other is the full ISO8601 date+time format. YYYY-MM-DD on the other hand depends on the DATEFORMAT setting
Update
I'd suggest performing this conversion as part of data loading though. Applying functions to a field prevents the server from using any indexes that cover the field. The server will have to scan the entire table in order to produce the final values used for filtering and sorting.
At least consider addd an indexed computed column that produces the file date

I want to convert the string to date type
Look at the first and 2nd statements you included, they are different in that you are missing a quote and you added an extra quote in the second one.
declare #filename varchar(20) = 'D181115.T000000'
select convert(datetime, '20' + substring(#filename, 2,2) + '-' + substring(#filename, 4,2) + '-' + substring(#filename,6,2))
Produces output:
2018-11-15 00:00:00.000

Related

Creating a unique ID that is a concatenation of several data types

I'm trying to make a unique ID in a view that is a concatenation of several data types. First I have DateID, which is a smallint, then I have LinkID which is an int, and lastly I have PicDateStamp which is a datetime.
I'm trying to create one unique ID, so I'm doing this:
Convert(varchar, T.DateID + '-' + P.LinkID + '-' P.PicDateStamp) as UTableID
For some reason it's returning a long date. I just want it to look something like (assume DateID is 22, LinkID is 74 and the date of PicDateStamp is 1/15/2018): 22-74-20180115.
Can someone help me?
Presumably you are using SQL Server (the + for string concatenation suggests this).
Convert to strings before concatenation:
(convert(varchar(255), T.DateID, 121) + '-' +
convert(varchar(255), P.LinkID) + '-' +
convert(varchar(255), P.PicDateStamp, 121)
) as UTableID
Note that this uses convert() rather than cast() so you can specify the format you want for the dates.

Output year and month with a string

Trying to output something like:
2016,11
Using this:
SELECT
CONVERT(VARCHAR(20),YEAR(GETDATE()) + ',' + MONTH(GETDATE())) AS YearMonth
Am I missing something in convert? Because I am getting this error:
Conversion failed when converting the varchar value ',' to data type
int.
Thanks
Try this.
SELECT
CONVERT(VARCHAR(20),YEAR(GETDATE())) + ',' + CONVERT(VARCHAR(20), MONTH(GETDATE())) AS YearMonth
You might use CONVERT with 112 to reach a string without delimiters ("20161110"). Converting this to VARCHAR(*6*) will implicitly cut the day. One (in most cases positiv) side-effect: You will get a low month zero padded (e.g. 2016,04). Then I use STUFF to insert the ,:
SELECT STUFF(CONVERT(VARCHAR(6),GETDATE(),112),5,0,',')
If you do not like the zero padded month, you could replace the 0 in STUFF like this:
DECLARE #d DATETIME={d'2016-04-05'};
SELECT STUFF(CONVERT(VARCHAR(6),#d,112),5,CASE WHEN MONTH(#d)<10 THEN 1 ELSE 0 END,',')
You are missing converting the output of MONTH() to a string. Here is one method:
select datename(year, getdate()) + ',' + cast(month(getdate()) as varchar(255)) as YearMonth
datename() is convenient because it returns a string. Unfortunately, for month it returns the name of the month, rather than the number.
You could also do:
select replace(convert(varchar(7), getdate(), 120), '-', ',')
Or use format() in SQL Server 2012+:
select format(getdate(), 'yyyy,MM')

Two Digit date format in SQL

I have a table field AccID where I have to concatenate Name with Date like 'MyName-010415' in SQL query.
Date format is 01-04-2015 or 01/04/2015. But I want to display it like 010415.
For the date part, to get the format you want you, try this:
SELECT
RIGHT(REPLICATE('0', 2) + CAST(DATEPART(DD, accid) AS VARCHAR(2)), 2) +
RIGHT(REPLICATE('0', 2) + CAST(DATEPART(MM, accid) AS VARCHAR(2)), 2) +
RIGHT(DATEPART(YY, accid), 2) AS CustomFormat
FROM yourtablename
...
The DATEPART(DD, accid) will give you the day part and the same for mm and yy will give you the month and the year parts. Then I added the functions RIGHT(REPLICATE('0', 2) + CAST(... AS VARCHAR(2)), 2) to add the leading zero, instead of 1 it will be 01.
SQL Fiddle Demo
As #bernd-linde suggested, you can use this function to concatenate it with the name part like:
concat(Name, ....) AS ...
Also you can just SELECT or UPDATE depending on what you are looking for.
As in #bernd-linde's fiddle.
I am not sure which language you are using. Let take php as an example.
$AccID = $name.'-'.date('dmy');
OR before you save this data format the date before you insert the data in database.. or you can write a trigger on insert.
You need to use DATE_FORMAT to change format of your date and CONCAT to marge name with date.
Example:
SELECT CONCAT(name, '-', DATE_FORMAT(field,'%m%d%y'))
FROM tbl

Converting separate columns for mm, dd, and yr into a workable mm/dd/year format

Basically I have 3 separate columns in a table. I will call them SMonth, Sday, Syear. They are stored as numeric values for some reason. I can use the following string to format them into what looks like a date but doesn't allow me to use functions such as sort, order by, datediff or dateadd.
CAST(SMonth AS varchar(2)) + '/' + CAST(SDay varchar(2)) + '/' + CAST(SYear AS varchar(4))
Anyone know how to convert this into a workable date, without changing the table?
It doesn't matter how it looks as long as I can use it ie a date or datetime makes no difference.
Thanks in advance.
Just convert your result into a date or datetime.
DECLARE #SMonth AS INT = 12
DECLARE #SDay AS INT = 31
DECLARE #SYear as INT = 2013
SELECT CONVERT(DATE,CAST(#SMonth AS varchar(2)) + '/' + CAST(#SDay AS varchar(2)) + '/' + CAST(#SYear AS varchar(4)))
you should convert format the string as yyyy/mm/dd in order to make sure that SQL Server uses ODBC canonical format
SELECT CONVERT(date, CONVERT(varchar, Syear) + '/' + convert(VARCHAR, SMonth) + '/' + convert(VARCHAR, SDay ) )
Otherwise it your results could depend on the default dateformat or someone changed it using SET DATEFORMAT, for example:
05/10/2013 could mean
May 10, 2013 if the DATEFORMAT is U.S.
October 5, 2013 if the DATEFORMAT is Brithish / French
see this for complete reference of dateformat

SQL Change format of datetime to specific style

I'm trying to convert a datetime value to a specific format, but noe of the style codes seem to do what I want. I tried the SQLUSA post on style codes, but none of them are quite right.
I have a column where the date/time is stored as yyyy-mm-dd hh:nn:ss (24 hour time)
I have a select statement were I want to take this column, but express the date as: mm/dd/yyyy hh:nn:ss AM/PM
The closest I've come is:
CONVERT(varchar,[datetimecolum],22) AS [newcolumnname]
but that only gives me a 2 digit year, not a century year (yyyy).
Any ideas? I'm totally lost. :(
Firstly, datetime fields are not stored in a specific string format, or but as a serial number. So what you see on screen is not what is stored but rather your database tool's default rendering of the date. Secondly why are you doing this in SQL? If you're passing the value to an application, make the conversion there from a native type. Thirdly, I don't think 22 is a valid conversion code in TSQL. Check http://msdn.microsoft.com/en-us/library/ms187928.aspx, for more info.
From: http://msdn.microsoft.com/en-us/library/ms187928.aspx
Judging by all the other formats listed, it would infer just add 100 to the format number to get "with century" (yyyy).
Although according to the documentation (and my tests) there is no format 22 (or 122) - so you'll have to combine two other formats to get exactly what you need:
CONVERT(varchar,[datetimecolum],101) + ' ' + CONVERT(varchar,[datetimecolum],108) AS [newcolumnname]
SQLFiddle demo
I think this does it
select stuff(convert(varchar(20),getdate(),22),7,2,
CAST( DATEPART(yyyy,getdate()) as CHAR(4)))
This is close but no AM PM
select convert(varchar(100),getdate(),22),
+ ' ' + CAST(DATEPART(mm,getdate()) as CHAR(2))
+ '/' + CAST( DATEPART(dd,getdate()) as CHAR(2))
+ '/' + CAST( DATEPART(yyyy,getdate()) as CHAR(4))
+ ' ' + CAST(DATEPART(HH,getdate()) as CHAR(2))
+ ':' + CAST(DATEPART(mi,getdate()) as CHAR(2))
+ ':' + CAST(DATEPART(ss,getdate()) as CHAR(2))
This is a Even clunkier than my original, but it works, except you won't get leading zeros for hours or minutes. You could modify this code to do that as well, but it will get really messy then, so I leave that to you ;-)
In other words, if the date + time is
3/1/2012 10:01:35 PM,
you will instead get:
3/1/2012 10:1:35 PM
Irritating, eh?
Anyway, here you go. Hope this helps.
SELECT dt.ID,
CASE WHEN EXISTS(SELECT DATEPART(HH, mt.TheDate)
FROM MyTable AS mt
WHERE mt.ID = dt.ID
AND (DATEPART(HH, mt.TheDate)) > 12)
THEN
(SELECT
CONVERT(varchar,(MONTH(dt.TheDate))) + '/' +
CONVERT(varchar,(DAY(dt.TheDate))) + '/' +
CONVERT(varchar,(YEAR(dt.TheDate))) + ' ' +
CONVERT(varchar, DATEPART(HH, dt.TheDate)-12) + ':' +
CONVERT(varchar,(DATEPART(mi, dt.TheDate))) + ':' +
CONVERT(varchar,(DATEPART( ss, dt.TheDate))) + ' PM')
ELSE
(SELECT
CONVERT(varchar,(MONTH(dt.TheDate))) + '/' +
CONVERT(varchar,(DAY(dt.TheDate))) + '/' +
CONVERT(varchar,(YEAR(dt.TheDate))) + ' ' +
CONVERT(varchar, DATEPART(HH, dt.TheDate)) + ':' +
CONVERT(varchar,(DATEPART(mi, dt.TheDate))) + ':' +
CONVERT(varchar,(DATEPART( ss, dt.TheDate))) + ' AM') END As FullDate
FROM MyTable AS dt
you need to do it in 2 parts and you need to use stuff to remove millisecond.I will update if find an other way to get rid of millisecond
SELECT CONVERT(VARCHAR(10), GETDATE(), 101)+' '+STUFF(RIGHT(CONVERT(VARCHAR(26), GETDATE(), 109),14),9,4,'')
output : 09/13/2012 11:15:21PM
Edit: incase you want space before AM/PM then use ' ' instead of '' in stuff
SELECT CONVERT(VARCHAR(10), GETDATE(), 101)+' '+STUFF(RIGHT(CONVERT(VARCHAR(26), GETDATE(), 109),14),9,4,' ')
output : 09/13/2012 11:15:59 PM