zoukankan      html  css  js  c++  java
  • SQL 格式化DateTime 类型

    格式化 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
    

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

  • 相关阅读:
    php编程 之php基础 表单
    javascript/ajax和php 进阶 之 项目实战
    php编程 之 php基础三
    Ajax基础1
    JavaScript编程基础2
    css3基础一
    html超文本标记语言基础一
    表连接、存储过程及基本编程
    五种函数、子查询及分页查询思路
    数据库与表的创建及增删改查
  • 原文地址:https://www.cnblogs.com/Music/p/1790777.html
Copyright © 2011-2022 走看看