从varchar转换为datetime

时间:2014-12-04 05:20:01

标签: sql-server tsql

 declare @FromDate varchar(30)
 set @FromDate= '2014-06-06'

我需要将@FromDate转换为datetime

set @fromdate = convert(datetime,  @fromdate, 126)

然后我需要格式为'2014-06-06 00:00:00.000'的输出。

有人可以建议如何执行此转换吗?

2 个答案:

答案 0 :(得分:1)

DECLARE @FromDate VARCHAR(30) SET @FromDate = '2014-06-06'
DECLARE @FromDateDT DATETIME SET @FromDateDT =  @FromDate
-- DECLARE @FromDateDT DATETIME SET @FromDateDT =  CONVERT(DATETIME, @FromDate) -- It's the same as line above
SET @FromDate = CONVERT(VARCHAR, @FromDateDT, 120)
SELECT  @FromDate
SET @FromDate = CONVERT(VARCHAR, @FromDateDT, 121)
SELECT  @FromDate

或简单

SELECT CONVERT(VARCHAR, CONVERT(DATETIME, '2014-06-06'), 121)

其他一些格式:

https://anubhavg.wordpress.com/2009/06/11/how-to-format-datetime-date-in-sql-server-2005/

随意问。

答案 1 :(得分:0)

试试这个

DECLARE @FromDate varchar(30)
SET @FromDate= '2014-06-06'
SELECT CONVERT(VARCHAR, CONVERT(DATETIME, @fromdate), 21)