在SQL Server中将字符串ddmmyyyyhhmi转换为yyyy

编程入门 行业动态 更新时间:2024-10-26 10:31:06
在SQL Server中将字符串ddmmyyyyhhmi转换为yyyy-mm-dd(Convert a string ddmmyyyyhhmi into yyyy-mm-dd in SQL server)

如何将字符串ddmmyyyyhhmi转换为yyyy-mm-dd ?

字符串210420161701 ( varchar )进入2016-04-21 ( datetime数据类型)。

我尝试了子串,转换,转换的组合,但似乎无法使其工作。

请帮助谢谢。

how can I convert a string ddmmyyyyhhmi into yyyy-mm-dd?

A string 210420161701 (a varchar) into 2016-04-21 (a datetime data type).

I tried a combination of sub-string, cast, convert but can't seem to make it work.

Please kindly help thanks.

最满意答案

前两行只是设置变量,但以下工作(只要格式始终相同)。 您可能还需要确保SQL安装的日期格式正确(SET DATEFORMAT)。 如果需要,您还可以将数据类型从日期更改为日期时间。

DECLARE @Date Varchar(100) = '210420161701' DECLARE @DateVariable date SELECT @DateVariable = SUBSTRING(@date,5,4) + '-' + SUBSTRING(@date,3,2) + '-' + SUBSTRING(@date,1,2) SELECT @DateVariable

The first 2 lines are just setting up the variable, but the following works (as long as the format is always the same). You may also need to make sure the date format of your SQL installation is correct (SET DATEFORMAT). You can also change the datatype from date to datetime if required.

DECLARE @Date Varchar(100) = '210420161701' DECLARE @DateVariable date SELECT @DateVariable = SUBSTRING(@date,5,4) + '-' + SUBSTRING(@date,3,2) + '-' + SUBSTRING(@date,1,2) SELECT @DateVariable

更多推荐

本文发布于:2023-08-06 07:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1445281.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   中将   SQL   Server

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!