Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL Server:将字符串转换为数字-从字符串转换日期和/或时间时转换失败_Sql_Sql Server - Fatal编程技术网

SQL Server:将字符串转换为数字-从字符串转换日期和/或时间时转换失败

SQL Server:将字符串转换为数字-从字符串转换日期和/或时间时转换失败,sql,sql-server,Sql,Sql Server,我在SQLServerManagementStudio中获得了一个数据集 数据如下所示 month Year ------------- Feb 2016 Jan 2015 我想用01作为dd创建一个数字日期。我试过了 CAST('01-'+ month +'-'+ year AS DATE) 也 两者都会导致此错误: 从字符串转换日期和/或时间时,转换失败 有人能教我如何将字符串转换成数字datetime/date吗?可能是因为连字符。您应该尝试使用空格: conver

我在SQLServerManagementStudio中获得了一个数据集

数据如下所示

month   Year
-------------
Feb     2016
Jan     2015
我想用01作为dd创建一个数字日期。我试过了

CAST('01-'+ month +'-'+ year AS DATE)

两者都会导致此错误:

从字符串转换日期和/或时间时,转换失败


有人能教我如何将字符串转换成数字datetime/date吗?

可能是因为连字符。您应该尝试使用空格:

convert(datetime, '01 '+ month +' '+ year, 106)
另一种可能是
month
包含无效值。在SQL Server 2012+中,使用
try\u convert()
可避免该问题:

try_convert(datetime, '01 '+ month +' '+ year, 106)

另一个选项是将concat与convert if 2012一起使用+

Select convert(datetime, concat(1,month ,year), 106)
使用此代码

convert(datetime, concat('01-', mnth , '-',yr), 106) AS d 

现在可能有一个解决方案,您应该考虑更改数据类型,以将日期信息存储在适当的数据类型中。在这种情况下,可能是日期。将其存储为字符串充满了不需要的挑战。需要注意的是,
CONCAT
在SQL Server 2012中是新版本,因此如果OP使用早期版本,他将无法使用此版本。需要注意的是,
CONCAT
在SQL Server 2012中是新版本,因此如果OP使用早期版本,他将无法使用此版本
convert(datetime, concat('01-', mnth , '-',yr), 106) AS d