代码改变世界

SQL 格式化DateTime 类型

2010-08-02 21:17  音乐让我说  阅读(782)  评论(0编辑  收藏  举报

格式化 SQL DateTime 类型

 

代码如下:

USE [MyDemo]
GO
/****** Object:  UserDefinedFunction [dbo].[FormatDateTime]    Script Date: 08/01/2010 16:28:23 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[FormatDateTime]
(
	@Date datetime,
	@formatStr varchar(20)
)
returns varchar(16)
as
begin
declare @tempstr varchar(20),@index int,@retStr varchar(20),@formatLen int,@str1 varchar(6),@str2 varchar(6),@str3 varchar(6),@j int
declare @tempformat varchar(20)
select @tempformat=@formatStr,@formatStr = Upper(@formatStr),@index=-1,@retstr=''
if @formatStr='MM/DD/YYYY'
	set @retstr= convert(varchar(10),@date,101)
else if @formatstr='YYYY-MM-DD'
	set @retstr = Convert(char(10),@Date,20)
else if @formatStr='YYYY.MM.DD'
	set @retstr= Convert(varchar(10),@Date,102)
else if @formatStr='YYYY/MM/DD'
	set @retstr= Convert(varchar(10),@Date,111)
else if @formatStr='DD/MM/YYYY'
	set @retstr= Convert(varchar(10),@Date,103)
else if @formatStr='DD.MM.YYYY'
	set @retstr= Convert(varchar(10),@Date,104)
else if @formatStr='DD-MM-YYYY'
	set @retstr= Convert(varchar(10),@Date,105)
else if @formatStr='YYYYMMDD'
	set @retstr= Convert(varchar(10),@Date,112)
else
	begin
		select @tempformat=@formatStr,@formatLen = len(@formatStr)
		if @formatLen>8
			begin
				set @index=charindex('M',@tempformat)
				select @str1=right(left(@tempformat,@index-1),@index-5),@str2=right(@tempformat,@formatLen-@index-1)
				select @index=charindex('D',@str2),@str3=@str2
				set @str2=left(@str2,@index-1)
				set @str3=right(@str3,len(@str3)-@index-1)
			end
		select @tempstr = Convert(char(10),@Date,20),@str1=isnull(@str1,''),@str2=isnull(@str2,''),@str3=isnull(@str3,''),@j=0
		while @index <> 0
		begin
			set @index = charindex('-',@tempstr)
			if @j=0
				select @retstr=left(@tempstr,@index-1)+@str1,@j=@j+1
			else 
				set @retstr=@retstr+left(@tempstr,@index-1)+@str2
			select @tempstr=right(@tempstr,len(@tempstr)-@index)
			set @index= charindex('-',@tempstr)
		end
		set @retstr=@retstr+@tempstr+@str3
end
return @retstr
end 
GO

 

代码结束。欢迎大家踊跃扩展,谢谢!