﻿<?xml version='1.0' encoding='UTF-8'?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>SQLServerCentral / Article Discussions / Article Discussions by Author / Discuss content posted by Gordon Klundt  / DateCeiling Function / Latest Posts</title><generator>InstantForum.NET v2.9.0</generator><description>SQLServerCentral</description><link>http://www.sqlservercentral.com/Forums/</link><webMaster>notifications@sqlservercentral.com</webMaster><lastBuildDate>Thu, 23 May 2013 03:53:10 GMT</lastBuildDate><ttl>20</ttl><item><title>RE: DateCeiling Function</title><link>http://www.sqlservercentral.com/Forums/Topic1026993-2765-1.aspx</link><description>I feel it's easier truncating a CONVERT(..., ..., 121), then CASTing again and adding the unit if the two dates differ - you can easily add a flag for ceiling/truncating:[code="sql"]CREATE FUNCTION dbo.DATECEILING( @f1 AS datetime, @part AS varchar(2), @is_ceiling AS bit )RETURNS datetimeASBEGINDECLARE @s1 varchar(21), @s2 varchar(21), @f2 datetimeselect @s1 = REPLACE( CONVERT( varchar(23), @f1, 121 ), '-', '' )IF @part = 'yy' SET @s2 = LEFT( @s1, 4 ) + '0101'IF @part = 'mm' SET @s2 = LEFT( @s1, 6 ) + '01'IF @part = 'dd' SET @s2 = LEFT( @s1, 8 )IF @part = 'hh' SET @s2 = LEFT( @s1, 12 ) + '00:00'IF @part = 'mi' SET @s2 = LEFT( @s1, 15 ) + '00'IF @part = 'ss' SET @s2 = LEFT( @s1, 17 ) SET @f2 = CAST( @s2 as datetime )IF @is_ceiling = 1 And @f1 &amp;gt; @f2BEGIN	IF @part = 'yy' SET @f2 = DATEADD( year, 1, @f2 )	IF @part = 'mm' SET @f2 = DATEADD( month, 1, @f2 )	IF @part = 'dd' SET @f2 = DATEADD( day, 1, @f2 )	IF @part = 'hh' SET @f2 = DATEADD( hour, 1, @f2 )	IF @part = 'mi' SET @f2 = DATEADD( minute, 1, @f2 )	IF @part = 'ss' SET @f2 = DATEADD( second, 1, @f2 )ENDRETURN @f2END[/code]</description><pubDate>Mon, 29 Nov 2010 08:07:06 GMT</pubDate><dc:creator>dbuendiab</dc:creator></item><item><title>RE: DateCeiling Function</title><link>http://www.sqlservercentral.com/Forums/Topic1026993-2765-1.aspx</link><description>A useful script, that is nearly there, but not quite.select dbo.dateceiling('2010-11-29 18:00:00.000','hh')should return 2010-11-29 18:00:00.000 in the same way that select ceiling(1.00) returns 1However, it doesn't - it returns 2010-11-29 19:00:00.000Looking at the code, the same would be true for minutes &amp; seconds where the rest of the datetime was zero.A small, but potentially important, bug.</description><pubDate>Sun, 28 Nov 2010 21:45:39 GMT</pubDate><dc:creator>antony-688446</dc:creator></item><item><title>DateCeiling Function</title><link>http://www.sqlservercentral.com/Forums/Topic1026993-2765-1.aspx</link><description>Comments posted to this topic are about the item [B]&lt;A HREF="/scripts/Date+Manipulation/71569/"&gt;DateCeiling Function&lt;/A&gt;[/B]</description><pubDate>Sat, 27 Nov 2010 12:05:36 GMT</pubDate><dc:creator>gklundt</dc:creator></item></channel></rss>