[英]Trying to convert nvarchar stored as datetime to int
I have a SQL date field that is stored as nvarchar(max)
. 我有一个SQL日期字段,存储为
nvarchar(max)
。
Example: 4/7/2016 12:50:03 AM
示例:
4/7/2016 12:50:03 AM
I need to convert this to int
. 我需要将其转换为
int
。
I have this: cast(convert(char(8), DateField,112) as int)
我有这个:
cast(convert(char(8), DateField,112) as int)
but I'm getting an error message 但我收到一条错误消息
Conversion failed when converting the varchar value '5/22/201' to data type int
将varchar值'5/22/201'转换为数据类型int时转换失败
Obviously, /
isn't an int
character. 显然,
/
不是int
字符。 Any suggestions?? 有什么建议么??
我相信如果将varchar强制转换为某个日期,它将可以正常工作(convert(char(8),cast(DateField as datetime),112)为int)
您可以replace
斜杠replace
为空格:
CAST(REPLACE(CONVERT(char(8),DateField,112),'/','') as int)
First, you should convert it to DATETIME
, then convert that to INT
. 首先,您应该将其转换为
DATETIME
,然后将其转换为INT
。 And don't count on the date portion being any particular length -- depending on the month and day of month, it can be from 8 to 10 chars long. 而且不要指望日期部分有任何特定的长度-根据日期和月份,它的长度可以是8到10个字符。
DECLARE @T TABLE (datefield VARCHAR(MAX))
INSERT @T VALUES ('4/7/2016 12:50:03 AM')
SELECT CAST(CONVERT(DATETIME, DateField) AS INT) FROM @T
I think you need a chain of conversions: string --> datetime --> string --> int 我认为您需要一系列转换:string-> datetime-> string-> int
cast(convert(char(8), convert(datetime, DateField, 101), 112) as int)
You might be able to rely on implicit conversions along the chain, but I prefer being explicit. 您也许可以依赖链中的隐式转换,但我更喜欢显式转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.