Reputation: 734
How can I convert single date values to date? For example in C# it is possible with the following;
int year = 2019;
int day = 1;
int month = 12;
DateTime newDate = new DateTime(year, month, day);
How is it possible in SQL Server?
I'm not asking static string value conversion such as; Convert(date, '2019-12-01')
because every element (year, month, day) in date must be parameter.
Upvotes: 1
Views: 92
Reputation: 43626
For 2012 version or later you can use DateFromParts:
DECLARE @year VARCHAR(4) = 2019;
DECLARE @day VARCHAR(2) = 1;
DECLARE @month VARCHAR(2) = 12;
SELECT DATEFROMPARTS ( @year, @month, @day )
for 2008 version or higher you can use:
SELECT CAST(CAST(@year AS varchar) + '-' + CAST(@month AS varchar) + '-' + CAST(@day AS varchar) AS DATE)
Upvotes: 3
Reputation: 3833
You may try this:
declare year varchar(5) = 2019;
declare day varchar(2) = 1;
declare month varchar(2) = 12;
declare newDate DateTime = (select Convert(date, year + '-' + month + '-' + date));
Upvotes: 0