SQL Server 2012 - varchar到目前为止

时间:2022-12-31 10:36:49

I am running views against a table that has dates stored as varchar(8) as DDMMYYYY, can someone please tell me how do I convert them to date format?

我正在运行一个表,其日期存储为varchar(8)作为DDMMYYYY,有人可以告诉我如何将它们转换为日期格式?

Thanks

1 个解决方案

#1


1  

In SQL Server 2012+, you can use datefromparts():

在SQL Server 2012+中,您可以使用datefromparts():

select datefromparts(right(col, 4) + 0, substring(col, 3, 2) + 0, left(col, 2) + 0)

I just added the + 0, because I'm not 100% sure if SQL Server will convert the arguments to integers.

我刚刚添加了+ 0,因为我不能100%确定SQL Server是否会将参数转换为整数。

Of course, you can also do it the "old" way as well:

当然,您也可以采用“旧”方式:

select convert(date, right(col, 4) + substring(col, 3, 2) + left(col, 2))

SQL Server recognized the format YYYYMMDD as a valid date.

SQL Server将格式YYYYMMDD识别为有效日期。

#1


1  

In SQL Server 2012+, you can use datefromparts():

在SQL Server 2012+中,您可以使用datefromparts():

select datefromparts(right(col, 4) + 0, substring(col, 3, 2) + 0, left(col, 2) + 0)

I just added the + 0, because I'm not 100% sure if SQL Server will convert the arguments to integers.

我刚刚添加了+ 0,因为我不能100%确定SQL Server是否会将参数转换为整数。

Of course, you can also do it the "old" way as well:

当然,您也可以采用“旧”方式:

select convert(date, right(col, 4) + substring(col, 3, 2) + left(col, 2))

SQL Server recognized the format YYYYMMDD as a valid date.

SQL Server将格式YYYYMMDD识别为有效日期。