FormatDateTime

Create function 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 select dbo. FormatDatetime(GetDate(),'YYYY元年MM月份DD日')

你可能感兴趣的:(J#)