您现在的位置:首页 >> 数据库 >> 数据库 >> 内容

一个SQL Server中的FormatDatetime函数

时间:2011/9/3 14:57:46 点击:

  核心提示:SQL Server中的类似于Delphi的FormatDateTime的函数Createfunction FormatDateTime(@Date datetime,@formatStr varch...

SQL Server中的类似于Delphi的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日')

@formatStr格式串支持:

MM/DD/YYYY

YYYY-MM-DD

YYYY.MM.DD

YYYY/MM/DD

DD/MM/YYYY

DD.MM.YYYY

DD-MM-YYYY

YYYYMMDD或者

类似YYYY年MM月DD日

YYYY  MM之间最多支持两个汉字,MM  DD之间也最多支持两个个汉字

select dbo. FormatDatetime(GetDate(),'YYYY元年MM月份DD日')

作者:不得闲 来源:原创
共有评论 1相关评论
发表我的评论
  • 大名:
  • 内容:
  • 盒子文章(www.2ccc.com) © 2024 版权所有 All Rights Reserved.
  • 沪ICP备05001939号