How can I format a datetime in SQL Server R2 to dd-MMM-yy (or dd-mon-yy)? - sql

Sample input: 2014-03-28 00:00:00.000
Sample output: 28-Mar-14
Current SQL:
SELECT StartDate
FROM myTable
Surprisingly, I could not find this particular format on StackOverflow for SQL Server so I thought I should add it to help save the next person some time.

Try this :-
SELECT REPLACE(CONVERT(VARCHAR,GETDATE(),6),' ','-')
Your query will be :-
SELECT REPLACE(CONVERT(VARCHAR,StartDate,6),' ','-') AS StartDate FROM myTable

New SQL:
SELECT REPLACE(CONVERT(CHAR(9), StartDate, 6),' ','-') AS FormattedStartDate
FROM myTable
Here's how it works in case you need to adjust for your needs:
CONVERT(CHAR(9), StartDate, 6) will output a CHAR(9). Make sure this is long enough for your desired output.
The value of 6 in the 3rd parameter tells CONVERT to output in the format
dd mon yy.
Notice that format has spaces which is why you need the REPLACE function if you want hyphens (-), slashes (/), or whatever instead of those spaces.
NOTE: If the date field is usually not null, CHAR(9) will use fewer bytes than VARCHAR. If there are a lot of blank data in the field, I would consider replacing the CHAR(9) with a VARCHAR because it will output fewer bytes in that case.

Related

Trying to convert SQL getdate into varchar with no in-between characters

I have a list of auto-generated tables in MS-SQLServer that differ only in the date listed at the end of the name.
The challenge is that I want to create a script that always references a table 'x days back'.
So for example if the table name would be:
dbo.tablename_20200825
I can get "close" to the date format I need as a string with the following statement and style
select convert(varchar(10), getdate(), 102);
However I still have those periods of separation between each part of the date.
How do I make the resulting string appear as '20200825' instead of '2020.08.25'
Thank you as always for any insight and help.
I think you're looking for 112
select convert(varchar(10), getdate(), 112);
Results
20200825
You can use format() to get exactly what you want:
select format(getdate(), 'yyyyMMdd')

Select a date in a string and convert it to datetime

I have a string like:
'SPY US 03/20/20 P45'
I want to select just the date from the string.
My current query is:
Select Ticker, SUBSTRING(Ticker, PATINDEX('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9]%',o.Ticker),8) AS 'myDate' FROM TABLE
This returns: 'SPY US 03/20/20 P45', 03/20/20
I want myDate to be in datetime.
I have tried various morphs of cast and convert, but they fail, presumably because they want the format to be in YYYY-MM-DD rather than MM/DD/YY.
My "smartest" attempt to convert was this:
CONVERT(DATETIME, SUBSTRING(o.Ticker, PATINDEX('%[0-9][0-9]/[0-9][0-9]/[0-9][0-9]%',o.Ticker),8),1)
After reading style guidelines here: https://www.w3schools.com/sql/func_sqlserver_convert.asp
but it still failed.
The ideal end-format for the date would be YYYY-MM-DD
Edited to add:
I have been fiddling with it and realized that I over simplied my question. The convert works if I just test it on a string, but the entire query involves several joins.
As I can understand you are looking for something like this.
You can use string_split() function to split string with blank space and then use try_cast() function to check each value whether it is a date.
declare #string as varchar(120) = 'SPY US 03/20/20 P4'
; with cte as (select
value
from string_split (#string, ' ')
)Select value from cte where try_cast (value as datetime) is not null
Live db<>fiddle demo.
So it turns out that there were a few entries in the column that didn't have friendly date format, so the patindex clause was returning nonsense.
For some reason that caused the entire operation to fail(rather than just returning null on the few entries that were failing).
Once I selected the entire (ultimately more complicated join statement) into a temp table, then I was able to try_convert the substring into a date and run my operations.

SQL Convert String to Date

I am trying to find a way of extracting the first part of line of string and separating as a date. The following is an example of some of the data.
17/10/12 lskell Still waiting for one more signature on the
I have tried casting the whole field as a date, and converting to a date, but these fail?
Would anyone have any ideas?
Try this for MySql
DATE_FORMAT(STR_TO_DATE(SUBSTRING_INDEX(columnname,' ',1), '%d/%m/%y'), '%Y-%m-%d')
If you know that
the first "word" in your string will always be a date
the date will always be separated from the rest of the string by a space
the date will have a consistent format
you are working in MySQL
then try this:
SELECT CAST(SUBSTRING_INDEX(myfield, ' ', 1) AS DATE) adate FROM mytable;
Try:
SELECT SUBSTRING('10/17/12 lskell Still waiting for one more signature on the', 1, 8)
(assuming date comes in this format)
-- MYSQL:
SELECT Str_to_Date(Left(yourstring,8),'%d/%m/%y') from yourtable;
-- Oracle
SELECT TO_DATE(left(yourstring,8),'dd/mm/yy')
from your table;
--- sql server
SELECT CONVERT(DATETIME,left(yourstring,8),120) from your table;

How to separate this field into two columns

I've got a seamingly simple problem to solve that normally would be fairly easy. I've got a field that contains a DateTime portion, as well as a trailing text portion. I now need to split this field into two discrete fields - DateTime and Varchar. Now for the little gotcha. The data has been saved with two different date formats which has resulted in the filed looking a 'lot' like this:
amendmentnote
----------------------------------------------------------------------
30/07/2010 11:39:55: Booking status change from On Option to Cancelled
5/5/2010 10:1:8 : New
as you can see, the dates are in two completely different formats. I'd like to somehow see it parsed out as:
dateofnote | note
----------------------------------------------------------------------
30/07/2010 11:39:55 | Booking status change from On Option to Cancelled
05/05/2010 10:01:08 | New
is this easily do-able??
cheers
jim
Easily? No. Do-able. Yes, if we can make some assumptions. If it is the case that the text never contains a colon, you could do:
Declare #Data Table ( Data Varchar(max) )
Insert #Data(Data) Values('30/07/2010 11:39:55: Booking status change from On Option to Cancelled')
Insert #Data(Data) Values('5/5/2010 10:1:8 : New')
Set DateFormat DMY
Select Cast(Reverse(Substring(Reverse(Data), CharIndex(':', Reverse(Data)) + 1, Len(Data))) As DateTime)
, LTrim(Reverse(Substring(Reverse(Data), 1, CharIndex(':', Reverse(Data)) - 1)))
From #Data
It's do-able, but it'll be ugly.
You can use string functions to find the third colon in the amendmentnote field, and anything to the right of the third colon will be your note.
As for the date, you should again be able to use string functions to reformat the date portion, although you'll most likely need lots of substrings to make it work.
My only concern would be if the date formats entered are MM/DD/YYYY for one entry, and DD/MM/YYYY for the other.
Based on what's provided, use:
SELECT CONVERT(DATETIME,
SUBSTRING(t.amendmentnote, 1, LEN(SUBSTRING(t.amendmentnote, 1, PATINDEX('%: %', t.amendmentnote)))-1),
103),
LTRIM(SUBSTRING(t.amendmentnote,
LEN(SUBSTRING(t.amendmentnote, 1, PATINDEX('%: %', t.amendmentnote)))+1,
LEN(t.amendmentnote)))
FROM YOUR_TABLE t
Being a DATETIME, you can use CAST/CONVERT to format it as you like - don't store "presentation" data.
Bad data is bad data - this is a mine field you'll have to navigate, isolating rows that won't match the pattern in the query & deal with appropriately.
Once in a DateTime column, they'll be in the standard DateTime format. How they're presented once queried at that point is up to you.
So, once you split your data into your DateOfNote and Note columns, you can Convert the DateOfNote to VarChar and apply a format to get what you want.
Convert(NVARCHAR, DateOfNate, 103) will get you there (I think: double check the format style there at the end).
Edit Based on your question, it looks like you wanted more help with the formatting. However, on the splitting the column, you'll need to use string functions. I'd find the index of that last colon, store it in a local variable, and then use substring to find the datetime (left of that last colon) and the note (right of last colon).

Easy way to force DATEPART to output as fixed-length?

When I do for example DATEPART(mm, GETDATE()) I get the result of the month being "8" for August. If i did the same thing in December I would get "12". Those are two different length results.
Is there a way to get the DATEPART results to always be a fixed length? So that for example the months would show up as 08 or 12. And days would be 05 and 30.
More Details:
I'm using a derived column transformation in SSIS to take a server datestamp, and remove all the formatting (spaces, colons, dashes, etc) in order to use it as part of a Primary Key.
My forumula that currently works is below, however it results in variable lenght results which is not ideal. I would like to get all results to be the same lenght.
((DT_STR,4,1252)DATEPART("yyyy",createDate)) + ((DT_STR,2,1252)DATEPART("mm",createDate)) + ((DT_STR,2,1252)DATEPART("dd",createDate)) + ((DT_STR,2,1252)DATEPART("hh",createDate)) + ((DT_STR,2,1252)DATEPART("mi",createDate)) + ((DT_STR,2,1252)DATEPART("ss",createDate)) + ((DT_STR,2,1252)DATEPART("ms",createDate))
Input looks like this:
9/11/2008 8:50:47:300 PM
Results look like:
20089112050473
Results should look like:
20080911205047300
SELECT RIGHT(100+DATEPART(mm, GETDATE()),2)
EDIT based on new info
- to get your timestamp to a fixed string of numbers:
SELECT REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(varchar(23), GETDATE(), 121),'-',''),':',''),' ',''),'.','')
The return type of DATEPART is int. The moment you ask for 05, is no longer and int but a string (char, varchar, nchar, nvarchar etc). As long as you understand the difference and you are OK with it, there are all sort of manipulations you can do to format the string as you whish, a good example being the one DJ showed. In truth though the proper place for such manipulations is on the client reporting, not on the server.
You can use CONVERT to grab a fixed-length date, for example:
SELECT CONVERT(nvarchar(30), GETDATE(), 126)
Which will show:
2006-04-18T09:58:04.570
which every variable in a fixed position.
Building on Andomar's example above:
SELECT REPLACE(REPLACE(REPLACE(REPLACE(
CONVERT(nvarchar(30), GETDATE(), 126),'-',''),'.',''),':',''),'T','')
Which will show:
20060418095804570
Caution: using a timestamp as a primary key WILL eventually bite you in the butt. Also, a primary key that is a number will be faster than a long string like this, so consider changing your algorithm to use a numeric conversion of the timestamp rather than a string.
Solution #2 Use a .NET user-defined function that wraps DateTime.ToString() so you can pass a specific format ("yyyymmddHHMMss" or whatever). Given the number of casts and replacements, it's possible this might perform just as well as straight T-SQL.