Essential SQL Server Date Time Functions


Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in D:\InetPub\vhosts\kwu-1639.package\kennywu.info\wwwroot\wp-content\plugins\wp-syntax\wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in D:\InetPub\vhosts\kwu-1639.package\kennywu.info\wwwroot\wp-content\plugins\wp-syntax\wp-syntax.php on line 380

Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in D:\InetPub\vhosts\kwu-1639.package\kennywu.info\wwwroot\wp-content\plugins\wp-syntax\wp-syntax.php on line 380

Returns a datetime value for the specified year, month and day

CREATE FUNCTION [dbo].[ReturnDate](@YEAR INT, @MONTH INT, @DAY INT) RETURNS datetime
AS
    BEGIN
    RETURN dateadd(MONTH,((@Year-1900)*12)+@Month-1,@Day-1)
    END

Returns @DateTime at midnight; i.e., it removes the time portion of a DateTime value.

CREATE  FUNCTION DateOnly(@DateTime DateTime)
RETURNS datetime
AS
    BEGIN
    RETURN dateadd(dd,0, datediff(dd,0,@DateTime))
    END

Sample:

SELECT dbo.ReturnDate(YEAR(getdate()), MONTH(getdate()),1) -- returns the first day of the current month.
SELECT dbo.ReturnDate(YEAR(getdate()), MONTH(getdate())+1,0) -- returns the last day of the current month.

Go to there for details:
http://weblogs.sqlteam.com/jeffs/archive/2007/01/02/56079.aspx

Leave a Reply

Your email address will not be published. Required fields are marked *