我正在尝试这个
declare @OpeningTime varchar(10)
Declare @OpeningTimeFormatted time(7)
Set @OpeningTime= '12:00pm'
Set @OpeningTimeFormatted= (Select CONVERT(time, CONVERT(varchar,CONVERT(date, getdate()))+ @OpeningTime, 120))
Select @OpeningTimeFormatted
但它会引发错误:
Conversion failed when converting date and/or time from character string.
答案 0 :(得分:1)
您需要在时间和日期之间留出空格。 只需将OpeningTime更改为
即可Set @OpeningTime= ' 12:00pm'
或
Set @OpeningTimeFormatted= (Select CONVERT(time, CONVERT(varchar,CONVERT(date, getdate())) + ' ' + @OpeningTime, 120))
否则您的日期将显示为2017-02-1412:00pm
答案 1 :(得分:0)
你需要一个空间:
Set `@OpeningTimeFormatted= (Select CONVERT(time, CONVERT(varchar,CONVERT(date, getdate()))+ ' ' + @OpeningTime, 120))`
答案 2 :(得分:0)
您已将@OpeningTimeFormatted
声明为time(7)
- 它无法保留日期
我怀疑你想在特定时间得到当前日期,
因此,您要将@OpeningTimeFormatted
声明为datetime2
:
declare @OpeningTime varchar(10)
Declare @OpeningTimeFormatted datetime2
Set @OpeningTime= '12:00pm'
SET @OpeningTimeFormatted = convert(datetime2,
convert(char(10), getdate(), 120) +' '+
convert(char(8), @OpeningTime, 120),
120)
Select @OpeningTimeFormatted
结果:
14.02.2017 12:00:00 -- today, tomorrow of course the date would be different...
另一方面,如果您只想获得varchar中指定的时间,则只需要convert(time(7), @OpeningTime, 120)
。