In this example, we'll explore the usage of Date and Integer data types in SQL Server. The code snippets demonstrate how to manipulate and extract date-related information.
1. Sample Code: Calculating Easter Date for a Given Year
Below is a SQL script to calculate the Easter date for a given year:
DECLARE @Date DATE, @c INT, @n INT, @i INT, @k INT, @j INT, @l INT, @m INT, @d INT, @Year INT = 2025
SET @n = @Year - 19 * (@Year / 19)
SET @c = @Year / 100
SET @k = (@c - 17) / 25
SET @i = @c - @c / 4 - (@c - @k) / 3 + 19 * @n + 15
SET @i = @i - 30 * (@i / 30)
SET @i = @i - (@i / 28) * (1 - (@i / 28) * (29 / (@i + 1)) * ((21 - @n) / 11))
SET @j = @Year + @Year / 4 + @i + 2 - @c + @c / 4
SET @j = @j - 7 * (@j / 7)
SET @l = @i - @j
SET @m = 3 + (@l + 40) / 44
SET @d = @l + 28 - 31 * (@m / 4)
SELECT EasterDate = CAST(@Year AS VARCHAR) + '-' + CAST(@m AS VARCHAR) + '-' + CAST(@d AS VARCHAR)
2. Retrieve Date Information Using SQL Server Functions
The following SQL queries return various date components such as the year, week, month, and the current date and time:
-- Retrieve various components of the current date
SELECT DATENAME(year, GETDATE()) AS Year,
DATENAME(week, GETDATE()) AS Week,
DATENAME(dayofyear, GETDATE()) AS DayOfYear,
DATENAME(month, GETDATE()) AS Month,
DATENAME(day, GETDATE()) AS Day,
DATENAME(weekday, GETDATE()) AS Weekday;
-- Higher precision datetime functions
SELECT SYSDATETIME() AS 'DateAndTime', -- returns datetime2(7)
SYSDATETIMEOFFSET() AS 'DateAndTime+Offset', -- datetimeoffset(7)
SYSUTCDATETIME() AS 'DateAndTimeInUtc'; -- returns datetime2(7)
-- Lesser precision datetime functions
SELECT CURRENT_TIMESTAMP AS 'DateAndTime', -- note: no parentheses
GETDATE() AS 'DateAndTime',
GETUTCDATE() AS 'DateAndTimeUtc';
3. Example of Date Output
Here’s an example of a date output in SQL Server:
References
For further details and in-depth exploration, check out the original article on the Simple Talk Website.

No comments:
Post a Comment