Skip to content
Related Articles

Related Articles

DATEFROMPARTS() Function in SQL Server

Improve Article
Save Article
Like Article
  • Last Updated : 18 Jan, 2021

DATEFROMPARTS() function :
This function in SQL Server is used to return a date from the given values of year, month and day.

Features :

  • This function is used to find a date from the stated values of year, month and day.
  • This function comes under Date Functions.
  • This function accepts three parameters namely year, month and day.
  • This function cannot include any time with the stated date.

Syntax :

DATEFROMPARTS(year, month, day)

Parameter :
This method accepts three parameters as given below :

  • year : It is the year specified which is of 4 digits.
  • month : It is the month specified which is from 1 to 12.
  • day : It is the day specified which is from 1st to 31st.

Returns :
It returns a date from the given values of year, month and day.

Example-1 :
Using DATEFROMPARTS() function and getting the date specified.

SELECT DATEFROMPARTS(2021, 01, 04);

Output :

2021-01-04

Example-2 :
Using DATEFROMPARTS() function with a variable and getting the date specified.

DECLARE @year Int;
SET @year = 2012;
SELECT DATEFROMPARTS(@year, 09, 13);

Output :

2012-09-13

Example-3 :
Using DATEFROMPARTS() function with three variables and getting the date specified.

DECLARE @year Int;
DECLARE @month Int;
DECLARE @day Int;
SET @year = 2016;
SET @month = 08;
SET @day = 29;
SELECT DATEFROMPARTS(@year, @month, @day);

Output :

2016-08-29

Example-4 :
Using DATEFROMPARTS() as a default value in the below example and getting the output.

CREATE TABLE date_from_parts
(
    id_num        INT IDENTITY, 
    message        VARCHAR(150) NOT NULL, 
    generated_at DATETIME NOT NULL
    DEFAULT DATEFROMPARTS(2001, 4, 7), 
    PRIMARY KEY(id_num)
);
INSERT INTO date_from_parts(message)
VALUES('First Message');

INSERT INTO date_from_parts(message)
VALUES('date_from_parts');
SELECT 
    id_num, 
    message, 
    generated_at
FROM 
    date_from_parts;

Output :

S.No.id_nummessagegenerated_at
11First Message07.04.2001 00:00:00
22date_from_parts07.04.2001 00:00:00

Here, firstly you need to create a table then insert values into it then generate the required output using DATEFROMPARTS() function as a default value.

Note : For running above code use sql server compiler, you can also use a online compiler.

Application :
This function is used to find the date from the specified values year, month and day.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!