NVARCHAR到datetime [英] NVARCHAR to datetime

查看:126
本文介绍了NVARCHAR到datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我的数据库表中有一个字段,它以YYMMDD格式存储日期,但字段的数据类型是NVARCHAR(60)。我需要将此字段显示为YYYY-MM-DD格式。请帮帮我。



我尝试过:



我尝试过以下语法但结果显示相同。



Hi everyone,

I have a field in my DB table which stores date in YYMMDD format, but the data type of field is NVARCHAR (60). I need to display this field as YYYY-MM-DD format. Please help me on this.

What I have tried:

I have tried below syntax but result is showing as same.

CONVERT(nvarchar, [EFT Trans_ Date], 120)

推荐答案

简单:更改数据库设计。

永远不要存储日期(或纯字符串数据之外的其他内容,如名称NVARCHAR或VARCHAR列中的地址和地址始终以适当的数据类型存储数据。对于整数值,即INT,对于浮点,它是FLOAT或DECIMAL。对于日期,即DATE,DATETIME或DATETIME2。



如果你不这样做,将会使你的工作变得更加困难,并让你自己开放随着时间的推移,要输入的数据越来越难以修复。



因此,请更改数据库设计,并将NVARCHAR列迁移到正确的数据类型。这可能看起来像很多毫无意义的工作,但它会为你节省大量的时间和心痛。
Simple: change your database design.
Never store dates (or anything other than "pure" string data like names and addresses) in NVARCHAR or VARCHAR columns always store data in appropriate datatypes. For integer values, that is INT, for floating point it's FLOAT or DECIMAL. For dates, that is DATE, DATETIME, or DATETIME2.

If your don't, will are making your job a whole load harder as well as leaving yourself open for bad data to enter which becomes increasingly harder to fix as time goes on.

So change your DB design, and migrate your NVARCHAR columns to the correct datatype. IT may seem like a lot of pointless work, but it will save you a huge amount of time and heartache later.


我完全赞同OG。请注意,将格式为 YYMMDD 的字符串转换为正确的日期并不容易,因为缺少一个世纪(年龄)部分。例如:

880521 可能会进入: 18880521 19880521 20880521



从MS SQL Server 2012开始,你可以使用: DATEFROMPARTS(Transact-SQL) - SQL Server | Microsoft Docs [ ^ ]。注意:您必须将年,月和日作为整数值传递。因此,您必须将字符串 YYMMDD 拆分为部分和 convert [ ^ ]它们为正确的整数值。



分割文本是另一个难点,因为它取决于SQL服务器版本。

截至2012年,您需要使用 SUSTRING() [ ^ ]功能。

从2016年开始,您可以使用 STRING_SPLIT(Transact-SQL) - SQL Server | Microsoft Docs [ ^ ]



BTW:您可以创建user-defined function [ ^ ],获取 YYMMDD 文本并返回正确的日期时间(基于您的世纪/年龄逻辑)。
I completely agree with OG. Note, that converting string in format YYMMDD to proper date is not easy job, because a century (age) part is missing. For example:
"880521" may become into: 18880521 or 19880521 or 20880521

Starting from MS SQL Server 2012, you can use: DATEFROMPARTS (Transact-SQL) - SQL Server | Microsoft Docs[^]. Note: you have to pass year, month and day as integer values. So, you have to split string YYMMDD into parts and convert[^] them to proper integer values.

Spliting text is another difficulty, because it depends on SQL server version.
Up to 2012, you need to use SUSTRING()[^] function.
Starting from 2016, you can use STRING_SPLIT (Transact-SQL) - SQL Server | Microsoft Docs[^]

BTW: you can create user-defined function[^], which gets a YYMMDD text and returns a proper date time (based on your century/age logic).


这篇关于NVARCHAR到datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆