当前位置:数据库 > SQLServer >>

MS SqlServer2008中,关于一个datetime转换的问题

字段名为sqrq(即申请日期),内容为'2012-08-07 00:00:00',如果使用“select convert(varchar(10),sqrq,120) from T_test1 where id=1”,则显示的是"2012-08-07",除了参数120外,还有哪个参数可以直接输出显示为:“2012-08” ? 谢谢!
答案:没有参数,只能截取
select substring(convert(char(8),getdate(),120),1,7)
其他:可以用 year 和 month 函数;
selectCONVERT(varchar, getdate(), 120 )
2004-09-1211:06:08

selectreplace(replace(replace(CONVERT(varchar, getdate(), 120 ),'-',''),'',''),':','')
20040912110608

selectCONVERT(varchar(12) , getdate(), 111 )
2004/09/12

selectCONVERT(varchar(12) , getdate(), 112 )
20040912

selectCONVERT(varchar(12) , getdate(), 102 )
2004.09.12

其它我不常用的日期格式转换方法:

selectCONVERT(varchar(12) , getdate(), 101 )
09/12/2004

selectCONVERT(varchar(12) , getdate(), 103 )
12/09/2004

selectCONVERT(varchar(12) , getdate(), 104 )
12.09.2004

selectCONVERT(varchar(12) , getdate(), 105 )
12-09-2004

selectCONVERT(varchar(12) , getdate(), 106 )
12092004

selectCONVERT(varchar(12) , getdate(), 107 )
0912, 2004

selectCONVERT(varchar(12) , getdate(), 108 )
11:06:08

selectCONVERT(varchar(12) , getdate(), 109 )
091220041

selectCONVERT(varchar(12) , getdate(), 110 )
09-12-2004

selectCONVERT(varchar(12) , getdate(), 113 )
120920041

selectCONVERT(varchar(12) , getdate(), 114 )
11:06:08.177 - 20 或 120 (*)   ODBC 规范 yyyy-mm-dd hh:mm:ss[.fff] 
- 21 或 121 (*)   ODBC 规范(带毫秒) yyyy-mm-dd hh:mm:ss[.fff] 
 
select CONVERT(varchar, getdate(), 120 ) 
2004-09-12 11:06:08
 
所以你要2012-08
必须是:
select convert(varchar(7),sqrq,120) from T_test1 where id=1
 
其中120可以是20,21,121 你都已经得到年月日了,自己把年月截出来又不麻烦。直接取得年月的函数好像是没有的 参数做不,而且MSSQL没有日期格式的函数
select left(convert(varchar(10),sqrq,120),7) from T_test1 where id=1; 实现这样的功能不是很难,可能不是不熟悉SQL,我给你一个比较简单的方法:
SELECT  LEFT ( CONVERT ( varchar(10), sqrq,120), 7 ) FROM   T_test1  WHERE id=1

你可以多看一下:LEFT 、RIGHT、REPLACE等SQL内置功能函数,可以实现你输出的各种格式 

上一个:sqlServer2005已经建好a、b两张表,想把a表x,y,z字段中的值查出来,写入b表的l,m,n字段。该怎么做?
下一个:sqlserver模糊查询语句

Oracle
MySQL
Access
SQLServer
DB2
Excel
SQLite
SYBASE
Postgres
如果你遇到数据库难题:
请访问www.zzzyk.com 试试
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,