| by Arround The Web | No comments

SQL Server Datefromparts()

“This article will explore how to use the DATEFROMPARTS() function in SQL Server. As the name suggests, this function enables us to construct a date value from the year, month, and day inputs.

It may seem like a simple function, but it can come in handy when you need to create a set of dates from various inputs in a quick and effective method.”

Function Syntax and Parameters

The following illustrates the syntax of the DATEFROMPARTS() function.

DATEFROMPARTS ( YEAR, MONTH, DAY )

The function accepts three main arguments:

  1. year – this is an integer type denoting the year.
  2. month – defines the month part of the date as an integer value. Ranges from 1 to 12.
  3. day – specifies the day part of the date value. Must range from 1 to 31

The function then returns a DATE type from the provided inputs. If either of the provided input is missing or NULL, the function will return a NULL value.

Examples

The following example shows a simple usage of the DATEFROMPARTS() function in SQL Server.

SELECT DATEFROMPARTS(2022, 10, 10) AS today;

Result:

today
2022-10-10

Example 2

The example below uses the DATEFROMPARTS() with NULL input values.

SELECT
DATEFROMPARTS(2022, NULL, 10);

Return value:

(No COLUMN name)
NULL

Example 3

In the example below, we use the DATEFROMPARTS() function with an out-of-range input:

SELECT
    DATEFROMPARTS(2022, 13, 10);

In this case, the function returns an error as shown:

Msg 289, Level 16, State 1, Line 356
Cannot construct DATA TYPE DATE; SOME OF the arguments have VALUES that are NOT valid.

Final

In this short post, we discussed using the DATEFROMPARTS() function in SQL Server to construct a date value from the year, month, and day inputs.

Thanks for reading!!

Share Button

Source: linuxhint.com

Leave a Reply