日期:2014-05-18  浏览次数:20760 次

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 all
select '1-19' union all
select '233321' union all
select '随意字符'

select *, convert(datetime, case isdate(s) when 1 then s else '1900' end) from #

/*
s         
--------- -----------------------
2011-1-19 2011-01-19 00:00:00.000
1-19      1900-01-01 00:00:00.000
233321    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的说明就会发现,原来日期还有这么多格式。