Creating a date column from multiple columns? - sql

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)

Related

Looking to replace the year in SQL Server

I am converting a date using CONVERT(varchar,DateOfBirth,101) for birthdates.
I want to show these dates with the current year, I've tried REPLACE but you can't use wildcards with it and when I use DATEPART, it doesn't format with the right digits for month and day. I also can't add years because they are wildly different birthdates. Thanks.
If you want to display the date as a string in 101 format for current year, one option uses a direct format():
format(DateOfBirth, 'MM/dd/2020')
You can compute the current date dynamically:
format(DateOfBirth, concat('MM/dd/', year(getdate())))
On the other hand, if you want your result as a date, then you could use datefromparts():
datefromparts(year(getdate()), month(DateOfBirth), day(DateOfBirth))
If it is a datevalue, you can use FORMAT function. If it is a character value, you can use RIGHT and REPLACE.
DECLARE #dateValue DATETIME = '05/12/1999'
DECLARE #dateCharValue VARCHAR(12) = '05/12/1999'
SELECT FORMAT(#dateValue, 'MM/dd/2020')
SELECT REPLACE(#dateCharValue, RIGHT(#dateCharValue,4),2020)
--Result
05/12/2020
This could helped you:
The code CONVERT(varchar(5),GETDATE(),1) return this 05/27 and then just add the year of the date
SELECT CONVERT(varchar(5),GETDATE(),1) + '/' + cast(year(getdate()) as varchar)
Or
SELECT CONVERT(varchar(5),GETDATE(),1) + '/' + convert(varchar,year(getdate()))
The result of both:
05/27/2020 --(This is my current date n.n )
This work but if you use a string something like your example DateOfBirth will be the variable and if this is a string (DateOfBirth = '5/27/1987') you need to convert the string DateOfBirth to Date:
SELECT CONVERT(varchar(5),convert(date,DateOfBirth),1) + '/' + cast(year(GETDATE()) as varchar)
Or
SELECT CONVERT(varchar(5),convert(date,DateOfBirth),1) + '/' + convert(varchar,year(GETDATE()))
The Result of Both :
05/27/2020

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

Format varchar type and convert it to date variable

I have a varchar value in this format “YYYYMM-LL” where: YYYY is four digit year; MM is two digit month.LL is two digit length of reporting period. This is the number of whole months included in the calculations (from first to last day of each month).
My questions is how I could use this varchar value to decide two variables:#First_Date and #Last_Date.
Example: 201409-06
This scenario is for the six months ending in September of 2014.
The range of calendar dates in this scenario is 04/01/2014 through 09/30/2014.
So how could I use t-sql to find this two dates #First_Date : 04/01/2014 and #Last_Date: 09/30/2014.
Any help would be really appreciated!
You can do something like this:
select #firstdate = dateadd(month, 1 - cast(right('201409-06', 2) as int),
convert(date, left('201409-06', 6) + '01')
),
#lastdate = dateadd(day, -1,
dateadd(month, 1,
convert(date, left('201409-06', 6) + '01')
)
)
This parses the string to do the date arithmetic that you want. SQL Server recognizes a string in the form of "YYYYMMDD" as a date, regardless of internationalization settings.
And a SQL Fiddle.

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 Converting string MMM.YY to date

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')