1

我从日期的存储过程中获得价值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.

谢谢

4

1 回答 1

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'
于 2013-07-26T13:43:14.393 回答