SQL Converting string MMM.YY to date - sql

how do i convert/cast a column contains strings e.g. Jan.08,Feb.08.. into date format so that i can sort them?
Greatest Thanks!

I'd just format as a convertible string for the first of the relevant month, and then cast to datetime, e.g.
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...is an expression that will yield a datetime that should be sortable, so:
SELECT
YourMonthAndYearColumnName
FROM
YourTable
ORDER BY
CAST('1.' + YourMonthAndYearColumnName AS DATETIME)
...should do what you're looking for.

If you can make the assumption that all dates will be within the last ten years, you can use the following code:
select convert(datetime, replace('Jan.08', '.', ' 20'))
select convert(datetime, replace('Dec.08', '.', ' 20'))
That formats the string into the format "Jan 2008", which is unambiguous. "Dec.08" could be "8th December this year" or "The month of december 2008".
Or you could use Matt Gibson's suggestion of prepending a "1." to your date before conversion. That removes the ambiguity, and has the advantage of using whatever defaults that SQL server has for dates (i.e. 50 is 1950 and 49 is 2049).
select convert(datetime, '1.' + 'Jan.08')
select convert(datetime, '1.' + 'Dec.49')
select convert(datetime, '1.' + 'Jan.50')

Related

SQL convert datetime to varchar

I want to convert DATETIME to VARCHAR (month/day/year) like this:
10/09/2018 12:00:00.000
I tried using
Convert(VARCHAR(MAX),[Date & Time Added]),121)
but it returns
yyyy-mm-dd hh:mi:ss.mmm
I need the / format with time, I am Using SQL Server 2012.
You can use the FORMAT function:
SELECT FORMAT(GETDATE(), 'MM/dd/yyyy HH:mm:ss.fff')
-- 10/09/2018 00:58:52.557
Complete list of format specifiers is actually available in the .NET documentation.
If FORMAT function is unavailable you could simply format in a known format and use string functions to re-arrange the year, month, day and time parts. For example:
SELECT SUBSTRING(DateStr, 6, 2) + '/' + SUBSTRING(DateStr, 9, 2) + '/' + SUBSTRING(DateStr, 1, 4) + ' ' + SUBSTRING(DateStr, 12, 12)
FROM (
SELECT CONVERT(VARCHAR(23), GETDATE(), 126) -- ISO8601 / yyyy-mm-ddThh:mi:ss.mmm
) AS CA(DateStr)
-- 10/09/2018 01:12:50.833
SELECT CONVERT(VARCHAR(10), Date, 101) + ' ' + CONVERT(VARCHAR(12), Date, 114)
FROM (
SELECT GETDATE()
) AS CA(Date)
-- 10/09/2018 01:19:38:463
This is something that would usually be done in the presentation layer, but if you need to do it in the data layer you can use FORMAT (documentation here)
Syntax is: FORMAT ( value, format [, culture ] )
So in your case (edited to add AM/PM designation per your comments): FORMAT([Date & Time Added], 'dd/MM/yyy hh:mm:ss.fff tt')
Custom date format string options are detailed here

Creating a date column from multiple columns?

If a table has 3 columns for a person's date of birth (ex: BirthMonth, BirthDay, BirthYear), what is the best way to combine them into one column with a format of MM/dd/yy and (obviously) a date datatype? Thank you.
You say "...put them into one field with a format of MM/dd/yy and (obviously) a date datatype? " but a date type does not have a display format. That's a presentation concern.
SQL Server 2012 onwards:
DATEFROMPARTS(year, month, day)
or
cast((DATEFROMPARTS(year, month, day) as date) to cast to pure date and remove default time portion
e.g.
SELECT DATEFROMPARTS(2010, 12, 31) AS Result;
Simply, combine all 3 columns into YYYY-MM-DD and then convert this string into Datetime.
For example:
Select
cast(cast(Year as string) + '-' +
cast(Month as string) + '-' +
cast(Day as string) as datetime)
Now you can format it any date format.
For SQL Server 2012, use the DATEFROMPARTS() function as suggested by Mitch. For prior versions:
Assuming BirthMonth, BirthDay, and BirthYear are all integral values, you can cast them:
CAST(CAST(BirthYear AS varchar) + '-' + CAST(BirthMonth AS varchar) + '-' + CAST(BirthDay AS varchar) AS DATETIME)
Alternatively, you can do it like this:
DATEADD(MONTH, BirthMonth - 1, DATEADD(YEAR, BirthYear - 1900, BirthDay - 1));
This has the advantage of not doing any string conversions and it's not dependent on any date format. This utilizes the fact that SQL Server's internal representation for the date is the number of days since 1 January 1900.
If BirthMonth, BirthDay, and BirthYear are valid string values, then you can cast them directly:
CAST(BirthYear + '-' + BirthMonth + '-' + BirthDay AS DATETIME)
And if they are guaranteed to have 2 digits for both the month and day (and 4 or 2 digits for the year), then you can cast them in a more compact way without hyphens:
CAST(BirthYear + BirthMonth + BirthDay AS DATETIME)

Why does my query return records which doesn't meet the where clause conditions?

I have written a query which returns records with dates that are actually older than the mentioned date.
Declare #DateFrom date
Set #DateFrom= '02/Oct/2019'
SELECT 1, Convert(varchar(11), AppliedDateTime, 106)
FROM [MC_Tenders].[dbo].[AppliedWorks]
Where
Convert(varchar, AppliedDateTime,106) >= Convert(varchar, #DateFrom,106)
Applied dates are saved in table as datetime e.g. 2017-04-25 15:51:25.257
You are doing the comparison as strings rather than dates. Remove the conversion:
SELECT 1, Convert(varchar(11), AppliedDateTime, 106)
FROM [MC_Tenders].[dbo].[AppliedWorks]
WHERE AppliedDateTime >= #DateFrom;
Type 106 is dd mm yyyy. When you compare as strings, the strings are compared, not the dates. With format 106, the days are compared first, so: '18-10-2017' < '25-12-1900' because "1" < "2".
Just to finish Gordon Linoff's thought, your code should look something like this:
SELECT
1
, CAST(AppliedDateTime AS DATE) AS AppliedDate
FROM
[MC_Tenders].[dbo].[AppliedWorks]
WHERE
CAST(AppliedDateTime AS DATE) >= #DateFrom;
Edit: I'm assuming AppliedDateTime is actually stored as a datetime, or some data type other than DATE. The explicit CAST to the DATE type will strip out the time component and allow SQL to just compare the date component to your variable.

Date Conversion in SQL

I have a date in following format in my DB.
10/16 - mm/yy
I need to convert it to:
October/16
Is this possible?
If it's not possible then please tell me why.
This is not a date, it's missing the day, it's a bad way to store year/month. There should be a 4 digit year to avoid confusion and the year should be listed first to enable correct sorting, e.g. '2016/10' or a numeric value 201610.
You can cast it to a DATE first and then use a FORMAT to disply only month/year:
set dateformat myd;
select format(cast(mystupidcolumn + '/1' as date), 'MMMM/yy')
Or SUBSTR the month part and use a CASE.
try this format,
SELECT DATENAME(month, DATEADD(month, #mydate-1, CAST('2008-01-01' AS datetime)))
You can display date by using this code
select datename(month, YourColumnName) + '/' + right(YEAR(YourColumnName),2)
FROM yourTableName
Simply change yourColumnName with name of your table column and yourTableName with name of table.
Yes you can, and it depend in what database you use to call date functions
If you column Datetime format
SQL server DATENAME(Month, GETDATE())
MySQL database MONTHNAME(now())
otherwise
convert it will in your choice at database or you code logic
split the value and lookup at month enum or fake the date to be accepted and complete date format like 01/10/16
so do something like SELECT DATENAME(Month, datecolumn) + '/' + YEAR (datecolumn)
also you can use instead of Year function DATEPART(yy,datecolumn)
the way you do it with format will look like
CONVERT(VARCHAR(11),GETDATE(),106)
but excepted to get first 3 char of month JUN

Elegantly convert DateTime type to a string formatted "dd-mmm"

We have the following solution:
select
substring(convert(varchar(20),convert(datetime,getdate())),5,2)
+ ' ' +
left(convert(varchar(20),convert(datetime,getdate())),3)
What is the elegant way of achieving this format?
You can do it this way:
declare #date as date = getdate()
select replace(convert(varchar(6), #date, 6), ' ', '-')
-- returns '11-Apr'
Format 6 is dd mon yy and you take the first 6 characters by converting to varchar(6). You just need to replace space with dash at the end.
You can use the dateName function:
select right(N'0' + dateName(DD, getDate()), 2) + N'-' + dateName(M, getDate())
If you really want the mmm part to only have the tree-letter abbreviation of the month, you're stuck with parsing the appropriate conversion type, for example
select left(convert(nvarchar, getDate(), 7), 3)
The problem is that dateName doesn't have an option to get you the abbreviated month, and the abbreviation isn't always just the first three letters (for example, in czech, two months start with Čer). On the other hand, convert 7 always starts with the abbreviation. Now, even with this, I assume that the abbreviation is always three letters long, so it isn't necessarily 100% reliable (you could search for space instead), but I'm not aware of any better option in MS SQL.
DECLARE #t datetime = getdate()
SELECT CONVERT(VARCHAR(24),LEFT(#t,6),113)
Try this...
SELECT LEFT(CONVERT(NVARCHAR(10), GETDATE(), 6), 6)