转换日期和/或时间时失败

时间:2013-07-26 07:21:22

标签: sql-server sql-server-2008 stored-procedures

我从商店程序中获得价值的日期为3/25/13 10:06:38 AM,我想转换此03/25/2013 10:18:28。我怎样才能在sql server中转换它。因为当我在日期时间投出这个时我得到错误。低于@PODTimeOnly is varchar(255)这里我只投出时间,之后我想将日期转换为另一个变量。

SET @PODTimeOnly = cast(@PODTime as time)

错误味精:

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

由于

1 个答案:

答案 0 :(得分: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'