GENERATE_SERIES function is introduced in SQL Server 2022 version. It is a simple function that generates a series of numbers within a given interval. It requires compatibility level 160.
GENERATE_SERIES (start, stop, optional step)
start: This is the number that SQL Server will start the series from. You can use tinyint, smallint, int, bigint, decimal, or numeric data types for this parameter.
stop: This is the last value of generated numbers. stop parameter accepts the same data type as the start parameter.
step: This parameter is optional. It indicates the number of values to increment or decrement between the start and stop numbers. The default value is 1
Here are some simple examples using the GENERATE_SERIES function.
SELECT value FROM GENERATE_SERIES (1, 30, 2)
SELECT value FROM GENERATE_SERIES (30, 1, -2)
As you can see, you can increase and decrease the numbers by using the optional step parameter. Another task you can accomplish with this function is generating different data types rather than numbers. For example, you can generate date ranges. All you need to do is to use this function with the DateAdd function. In the following example, I generate 15 dates with help of the GENERATE_SERIES function, DATEADD function, and GETDATE() function.
SELECT DATEADD(DAY, value, GETDATE())
FROM GENERATE_SERIES(1,30,1)
You can customize the dates easily by changing the parameters of the DATEADD function. You can cast the DateTime and generate only Date or Time if you like. DateAdd function and Cast give you a lot of possibilities here.
No comments:
Post a Comment