2013-07-26 20 views
1

我从商店程序中获得的价值是3/25/13 10:06:38 AM,我想将其转换为03/25/2013 10:18:28。我怎样才能在sql服务器中进行转换。因为当我在日期时间中施放此错误时,我得到了错误。在@PODTimeOnly is varchar(255)下面我只投射时间,在此之后,我想在另一个变量中投射和存储日期。转换日期和/或时间时失败

SET @PODTimeOnly = cast(@PODTime as time) 

错误味精:

Conversion failed when converting date and/or time from character string. 

感谢

+1

如果你可以避免把它作为一个字符串放在第一位,那会更好。尽量将所有内容保存在适当的变量中('date' /'time' /'datetime' /'datetime2')。 –

回答

1

不知道我完全理解所需要的输出,但如果你不得不砍串在一起,以产生不同的格式的日期时间值,这可能工作。

DECLARE @strDate VARCHAR(50) = '3/25/13 10:06:38 AM', 
     @dtDate DATETIME, 
     @DateOnly VARCHAR(255), 
     @TimeOnly VARCHAR(255), 
     @output VARCHAR(255) 

-- cast to datetime first to verify its a valid date 
SET @dtDate = CAST(@strDate AS DATETIME) 

-- parse/cast date and time to seperate variables 
SET @DateOnly = CONVERT(VARCHAR(255),@dtDate,101) 
SET @TimeOnly = CONVERT(VARCHAR(255),@dtDate,108) 

-- duct tape them back together in the desired string format 
SET @output = @DateOnly + ' ' + @TimeOnly 

-- outputs '03/25/2013 10:06:38' 
SELECT @output AS 'NewStringDate' 
相关问题