Freigeben über


SQL Server Function to merge a date with a time

I use this when I need to join two fields. One has a date, the other has a time.

 

 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[util].[uf_MergeDate2Time]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
 DROP FUNCTION [util].[uf_MergeDate2Time]
 GO
 CREATE FUNCTION [util].[uf_MergeDate2Time](
       @date            DATETIME,
       @time            DATETIME
 )
 RETURNS DATETIME
 WITH EXECUTE AS CALLER
 AS
 /**********************************************************************************************************
 * UDF Name:        
 *        [util].[uf_MergeDate2Time]
 * Parameters:  
 *         @date            datetime - The date to merge
          @time            datetime - The time to merge
 * Purpose: This function returns a datetime of the @date variable concatendated to the @time variable.
 *
 * Example:
     select [util].[uf_MergeDate2Time]('12/25/2007', GETDATE())
 *              
 * Revision Date/Time:
 *    November 1, 2007
 *
 **********************************************************************************************************/
 BEGIN
     -- declare variables
     DECLARE @result datetime;
  
     -- determine half year date
     SET @result = CAST(LEFT(CONVERT(NVARCHAR(40), @date, 121), 10) + ' ' + RIGHT(CONVERT(NVARCHAR(40), @time, 121), 12) AS DATETIME)
  
  
     
 RETURN @result;
  
 END;
 GO
 SELECT [util].[uf_MergeDate2Time]('2007-12-25', GETDATE());
 GO

 

Technorati Tags: sql server 2005,SQL Function,SQL Server 2008,Katmai,Data Warehouse

Comments

  • Anonymous
    November 18, 2007
    I use this when I need to join two fields. One has a date, the other has a time.   IF EXISTS ( SELECT

  • Anonymous
    March 09, 2009
    simple way: UPDATE table SET Date=CONVERT(datetime, Date, 105) + CONVERT(datetime, Time, 108) fields are names date and time