首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

varchar转datetime解决方案

2012-03-18 
varchar转datetime有如下的一个需求:数据库表table1中有一个列column1,这个列的类型是varchar(max),现在需

varchar转datetime
有如下的一个需求:
  数据库表table1中有一个列column1,这个列的类型是varchar(max),现在需要把这个列中的数据转为日期类型(例:2011-01-19 12:45:12)并按日期来排序,这个列中的值不一定是一个合法的日期值,例如可以为以下值之一:
  "2011-1-19"
  "1-19"
  "233321"
  "随意字符";
   
  当能够转换成功时,返回转换后的值,否则返回"1900-1-1 00:00:00";

[解决办法]

SQL code
--> 测试数据:#if object_id('tempdb.dbo.#') is not null drop table #create table #(s varchar(9))insert into #select '2011-1-19' union allselect '1-19' union allselect '233321' union allselect '随意字符'select *, convert(datetime, case isdate(s) when 1 then s else '1900' end) from #/*s         --------- -----------------------2011-1-19 2011-01-19 00:00:00.0001-19      1900-01-01 00:00:00.000233321    1900-01-01 00:00:00.000随意字符  1900-01-01 00:00:00.000*/
[解决办法]
探讨
SQL code
--> 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(s varchar(9))
insert into #
select '2011-1-19' union all
select '1-19' union all
select '233321' union a……

[解决办法]
探讨

引用:
SQL code
--> 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(s varchar(9))
insert into #
select '2011-1-19' union all
select '1-19' union all
s……

[解决办法]
有时候还是自己想一下,例如你若看CONVERT的说明就会发现,原来日期还有这么多格式。

热点排行