如何格式化表里面的时间字段 
如下:
id   Datas 
1    20110109
2    20110109
3    20110109
4    20110109
5    20110109
6    20110109如何在sqlserver里面让它转换成
id   Datas 
1    201101
2    201101
3    201101
4    201101
5    201101
6    201101这样可以select convert(varchar(6),'20110109',112) 将单个20110109格式化成201101 但是只能转换单个,不能转换表字段
如我这样写select convert(varchar(6),Datas ,112) as Datas from table 就不行了,还请大侠们帮帮忙,sqlserver里面有没有这样的转换表中字段的函数?或如何实现。
 

解决方案 »

  1.   

    select convert(varchar(6),cast(Datas as datetime) ,112) as Datas from table
      

  2.   

    --> 测试数据:#tb
    if object_id('tempdb.dbo.#tb') is not null drop table #tb
    create table #tb([id] int,[Datas] datetime)
    insert #tb
    select 1,'20110109' union all
    select 2,'20110109' union all
    select 3,'20110109' union all
    select 4,'20110109' union all
    select 5,'20110109' union all
    select 6,'20110109'select convert(varchar(6),Datas ,112) as Datas from  #tb
      

  3.   

    经常调用这类格式可用计算列create table T(ID int identity,Dates datetime)
    go
    alter table T add NewCol as convert(varchar(6),Dates,112)--用计算列
    go
    insert T(Dates) select GETDATE()
    goselect NewCol from T
    /*
    201101
    */
      

  4.   

    id int ,
    Datas int 
      

  5.   

    看楼主上面的语句,那个字段是一个字符型的。如果是字符型的,还用去那么转吗?直接用:
    select left(Datas,6) as Datas from Table
      

  6.   

    select left(ltrim(cast(Datas as varchar(10))),6) as Datas from Table
      

  7.   

    if object_id('tempdb.dbo.#tb') is not null drop table #tb
    create table #tb([id] int,[Datas] int)
    insert #tb
    select 1,'20110109' union all
    select 2,'20110109' union all
    select 3,'20110109' union all
    select 4,'20110109' union all
    select 5,'20110109' union all
    select 6,'20110109'select LEFT([Datas],6) from #tb
    /*
    ----------------------
    (无列名)
    201101
    201101
    201101
    201101
    201101
    201101
      

  8.   

    covert(varchar(10) date,12);//dateformat yyyy-mm-dd