SQL Server 扩展一个支持类似。net 时间格式化的标量函数~
IF EXISTS(SELECT TOP 1 * FROM sys.objects WHERE name=N'uF_DateFormat' AND [type]='FN') DROP FUNCTION uF_DateFormat GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: hehai -- Create date: 2015-11-27 16:06:43 -- Description: 对指定的时间进行指定格式的转换 /* @formatString 年 份:yy / yyyy (15/2015) 月 份: mm/MM (1/01 11/11) 日 期:d/dd/D/DD (1/01 10/10) 小 时:h/hh/H/HH (6AM/06AM/6/06) h表示按照12时制格式化, H表示按照24时制格式化,若为h/hh时间最后有[AM 或 PM] (6PM/06PM/18/18) ------------------------------------------- 分 钟:mi/mz (10/10 1/01) 秒 钟:si/ss (1/01 10/10) 秒 钟:mss/ms (0/10/999 000/010/999) */ -- ============================================= CREATE FUNCTION uF_DateFormat ( @date DATETIME, -- 指定转换时间 @formatString NVARCHAR(30), -- 指定需要转换格式 @defaultIfdateIsNull NVARCHAR(30) -- 返回指定时间的指定转换格式结果字符 ) RETURNS NVARCHAR(30) AS BEGIN DECLARE @R NVARCHAR(30),@T NVARCHAR(5),@C CHAR(2)=N'AM' DECLARE @Y INT,@M TINYINT,@D TINYINT,@H TINYINT,@MI TINYINT,@SS TINYINT,@MS INT SET @Y=DATEPART([YEAR],@date) SET @M=DATEPART([MONTH],@date) SET @D=DATEPART([DAY],@date) SET @H=DATEPART([HOUR],@date) SET @MI=DATEPART([MINUTE],@date) SET @SS=DATEPART([SECOND],@date) SET @MS=DATEPART([MILLISECOND],@date) SET @R=@formatString SET @R=REPLACE(@R,N'yyyy',CAST(@Y AS NVARCHAR(4))) SET @R=REPLACE(@R,N'YYYY',CAST(@Y AS NVARCHAR(4))) SET @R=REPLACE(@R,N'yy',RIGHT( CAST(@Y AS NVARCHAR(4)),2)) SET @R=REPLACE(@R,N'YY',RIGHT( CAST(@Y AS NVARCHAR(4)),2)) SET @T=CAST(@M AS NVARCHAR(2)) IF @M<10 SET @T=N'0'+CAST(@M AS NVARCHAR(2)) SET @R=REPLACE(@R,N'MM',@T) SET @R=REPLACE(@R,N'mm',@T) SET @T=CAST(@D AS NVARCHAR(2)) IF @D<10 SET @T=N'0'+CAST(@D AS NVARCHAR(2)) SET @R=REPLACE(@R,N'dd',@T) SET @R=REPLACE(@R,N'DD',@T) SET @R=REPLACE(@R,N'dd',@T) SET @R=REPLACE(@R,N'd',@T) SET @T=CAST(@H AS NVARCHAR(2)) IF @H<10 SET @T=N'0'+CAST(@H AS NVARCHAR(2)) SET @R=REPLACE(@R,N'HH',@T) SET @R=REPLACE(@R,N'H',@T) -- 12小时制 -- SET @T=CAST(@H AS NVARCHAR(2)) IF @H>=12 BEGIN SET @C='PM' SET @H=24-12 SET @T=CAST(@H AS NVARCHAR(2)) END SET @R=REPLACE(@R,N'hh',@T) SET @R=REPLACE(@R,N'h',@T) SET @T=CAST(@MI AS NVARCHAR(2)) IF @MI<10 SET @T=N'0'+CAST(@MI AS NVARCHAR(2)) SET @R=REPLACE(@R,N'mi',@T) SET @T=CAST(@SS AS NVARCHAR(2)) IF @SS<10 SET @T=N'0'+CAST(@SS AS NVARCHAR(2)) SET @R=REPLACE(@R,N'ss',@T) SET @R=REPLACE(@R,N'si',@T) SET @T=CAST(@MS AS NVARCHAR(3)) IF @MS>=0 AND @MS<10 SET @T=N'00'+CAST(@MS AS NVARCHAR(1)) IF @MS>=10 AND @MS<100 SET @T=N'0'+CAST(@MS AS NVARCHAR(2)) SET @R=REPLACE(@R,N'ms',@T) SET @R=REPLACE(@R,N'mss',@T) RETURN @R END GO -- 年月日 SELECT dbo.uF_DateFormat(getdate(),'yyyyMMdd',NULL) SELECT dbo.uF_DateFormat(getdate(),'yyyy/MM/dd',NULL) SELECT dbo.uF_DateFormat(getdate(),'yyyy-MM-dd',NULL) SELECT dbo.uF_DateFormat(getdate(),'yyyy年MM月dd日',NULL) -- 年月日时分秒 SELECT dbo.uF_DateFormat(getdate(),'yyyyMMdd HH:mi:ss',NULL) -- 年月日时分秒 毫秒 SELECT dbo.uF_DateFormat(getdate(),'yyyy-MM-dd HH:mi:ss.ms',NULL)