简体   繁体   English

使用SQL Server中的格式将nvarchar转换为最新格式

[英]Casting nvarchar to date with a formatting in SQL-Server

I'm using SQL Server Management Studio. 我正在使用SQL Server Management Studio。 There is one table in my database containing dates which are stored as nvarchar(255). 我的数据库中有一张表,其中包含存储为nvarchar(255)的日期。 I want to migrate the data of this table to a new table which I call Converted_Dates and store this data as date. 我想将此表的数据迁移到一个新表,我将其称为Converted_Dates并将此数据存储为日期。 Also, I want them all to be formatted like this YYYY-MM-DD 另外,我希望它们都被格式化为YYYY-MM-DD

Currently the Dates table looks like this: 当前日期表看起来像这样:

**Dates**
15/6/2011 
16/6/2011
2013-03-30
2013-04-16
...

I want the new table to look like this: 我希望新表如下所示:

**Converted_Dates**
2011-06-15
2011-06-16
2013-03-30
2013-04-16
...

I execute this query but formatting of dates remains the same, only the data type changes from nvarchar(255) to date. 我执行此查询,但日期格式保持不变,只是数据类型从nvarchar(255)更改为日期。

    USE [reporting_database]
    GO
    INSERT INTO [dbo].[Converted_Dates]
    SELECT
        cast(Dates as date)


        FROM [dbo].[Dates]
    GO

Any advice on how to cast the data from the old table to a new one in a preferred format? 关于如何以首选格式将数据从旧表转换为新表的任何建议?

The value of date and datetime data type is not stored with format in sql server. datedatetime数据类型的值未以格式存储在sql server中。 If you want to see the date in a different format you can manipulate the way that date and datetime data types are displayed when converted to a varchar (or nvarchar , nchar , char ) data type using some built in functions. 如果要查看其他格式的日期,则可以使用一些内置函数来控制将日期和日期时间数据类型转换为varchar (或nvarcharncharchar )数据类型时的显示方式。

You should store your dates as date data type, and if you can format them at the application level, do so there. 您应该将日期存储为date数据类型,如果可以在应用程序级别格式化它们,请在此处进行格式化。 If you must format them in sql, then use convert() styles . 如果必须使用sql格式化它们,请使用convert()样式

select convert(char(10),getdate(),120) 

returns: 2017-05-01 回报: 2017-05-01


In sql server 2012+ you can use format() 在SQL Server 2012+中,您可以使用format()

 select format(getdate(),'yyyy-MM-dd') 

returns: 2017-05-01 回报: 2017-05-01

But format() is much slower, take a look here: format() is nice and all, but… - Aaron Bertrand 但是format()慢得多,请看这里: format()很不错,但是…-Aaron Bertrand

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM