sql日期格式转换函数_SQL转换日期

sql日期格式转换函数

介绍 (Introduction)

A common task for newbies is to learn how to do a SQL convert date and work to convert them date to other data types or covert other data types to Date.

对于新手来说,一项常见的任务是学习如何执行SQL转换日期并将其转换为其他数据类型或将其他数据类型转换为Date。

Here in this article we will explain how to work and convert dates to different formats or vice versa.

在本文的此处,我们将解释如何将日期转换为不同的格式,反之亦然。

要求 (Requirements)

  1. SQL Server installed. Starting in SQL Server 2008

    已安装SQL Server。 从SQL Server 2008开始

(Example)

The first example will be simple, we have a varchar column with a date in a table, but we need to convert the varchar to date. We need to do a SQL convert date.

第一个示例很简单,我们在表中有一个带有日期的varchar列,但是我们需要将varchar转换为date。 我们需要做一个SQL转换日期。

Here it is script to create the table with data:

这是使用数据创建表的脚本:

CREATE TABLE [dbo].[delivers](
  [productid] [tinyint] NOT NULL,
  [date] [nvarchar](100) NULL,
 CONSTRAINT [PK_delivers] PRIMARY KEY CLUSTERED 
(
  [productid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[delivers] ([productid], [date]) VALUES (1, N'02-03-2005')
INSERT [dbo].[delivers] ([productid], [date]) VALUES (2, N'03-05-2006')
INSERT [dbo].[delivers] ([productid], [date]) VALUES (3, N'04-05-2011')

We want to convert the column date from nvarchar(100) to a date.

我们想要将列日期从nvarchar(100)转换为日期。

To do it, we are going to try to modify the design of the table:

为此,我们将尝试修改表的设计:

sql日期格式转换函数_SQL转换日期_第1张图片

We will try to change the Data Type to smalldatetime:

我们将尝试将数据类型更改为smalldatetime:

sql日期格式转换函数_SQL转换日期_第2张图片

You will receive the following error message:

您将收到以下错误信息:

Saving changes is not permitted. The changes that you have made require the following tables to be dropped and re-created. You have either made changes to a table that can’t be re-created or enabled the option Prevent saving changes that require the table to be re-created.

不允许保存更改。 您所做的更改要求删除并重新创建下表。 您已经对无法重新创建的表进行了更改,或者启用了“防止保存需要重新创建表的更改”选项。

To solve this error, in SSMS go to Tools > Options menu:

要解决此错误,请在SSMS中转到“ 工具” >“ 选项”菜单:

sql日期格式转换函数_SQL转换日期_第3张图片

In Options, go to Designers >Table and Database Designers and uncheck the Prevent saving changes that require table re-creation:

在选项中,转到设计器>表和数据库设计器,然后取消选中阻止保存需要重新创建表的更改:

sql日期格式转换函数_SQL转换日期_第4张图片

This option will disable to option to prevent saving table recreation. When you modify the column data type, it requires table re-creation.

此选项将禁用为选项,以防止保存表重新创建。 修改列数据类型时,需要重新创建表。

Now, you can save the design and your table will be converted to date and the SQL convert date is completed:

现在,您可以保存设计,您的表将转换为日期,并且SQL转换日期已完成:

sql日期格式转换函数_SQL转换日期_第5张图片

转换功能 (Conversion functions)

T-SQL contains functions to convert data types. We will use CAST and CONVERT to do a SQL convert date.

T-SQL包含转换数据类型的函数。 我们将使用CAST和CONVERT进行SQL转换日期。

Let’s start with CAST first:

让我们先从CAST开始:

如何使用CAST将varchar,nvarchar,char,nchar转换为sql date (How to convert from varchar, nvarchar, char, nchar to sql date using CAST)

The following example, will show how to convert characters to a datetime date type using the CAST function:

下面的示例将说明如何使用CAST函数将字符转换为日期时间日期类型:

declare @vardate varchar(100)='03-04-2016'
select CAST(@vardate AS datetime) AS dataconverted;

The example declares a variable named vardate and then this variable that is a varchar is converted to datetime using the CAST function.

该示例声明一个名为vardate的变量,然后使用CAST函数将该变量varchar转换为datetime。

Note: For more information about the CAST function, refer to this link: CAST and CONVERT (Transact-SQL)

注意: 有关CAST函数的更多信息,请参考以下链接: CAST和CONVERT(Transact-SQL)

SQL如何使用CONVERT将日期从varchar,nvarchar,char,nchar转换为日期 (How to do a SQL convert date from varchar, nvarchar, char, nchar to date using CONVERT)

CONVERT is a function that can do the same than CAST in the previous scenario.

CONVERT是一项功能,可以与以前的方案中的CAST相同。

declare @vardate varchar(100)='03-04-2016'
select CONVERT(datetime, @vardate) as dataconverted

The T-SQL code is doing the same than cast, but it is using the CONVERT function. The advantage of CONVERT is that you can easily change the format of the date using the style argument.

T-SQL代码的作用与强制转换相同,但是它使用的是CONVERT函数。 CONVERT的优点是您可以使用style参数轻松更改日期格式。

For example, if you want the date in the ISO format, you can use the following T-SQL sentence:

例如,如果您想要ISO格式的日期,则可以使用以下T-SQL语句:

select CONVERT(nvarchar(30),getdate(), 121) as isoformat

如何在T-SQL中将SQL日期转换为不同的格式 (How to convert sql date into different formats in T-SQL)

The following example shows how to convert the date format in different formats.

下面的示例演示如何将日期格式转换为其他格式。

For Japananes format:

对于Japananes格式:

select CONVERT(nvarchar(30),getdate(), 111) as Japanformat

For USA format:

对于美国格式:

select CONVERT(nvarchar(30),getdate(), 110) as USAformat

For ANSI format:

对于ANSI格式:

select CONVERT(nvarchar(30),getdate(), 102) as ANSIformat

For British format:

对于英式格式:

select CONVERT(nvarchar(30),getdate(), 103) as Britishformat

For German format:

对于德语格式:

select CONVERT(nvarchar(30),getdate(), 104) as Germanformat

For Italian format:

对于意大利语格式:

select CONVERT(nvarchar(30),getdate(), 105) as Italianformat

For European default format:

对于欧洲默认格式:

select CONVERT(nvarchar(30),getdate(), 113) as EuropeDefaultformat

For ODBC Canonical:

对于ODBC Canonical:

select CONVERT(nvarchar(30),getdate(), 120) as ODBCCanonicalformat

You always have the option to use the FORMAT function to get the date in the format that you want:

您始终可以选择使用FORMAT函数以所需的格式获取日期:

SELECT FORMAT( getdate(), 'dd/MM/yy')

FORMAT is easier to handle dates and use the format of your preference, because you do not need to know the style. However, in my experience I see a lot of code using the CAST and CONVERT functions so, it is better to know them.

FORMAT更容易处理日期并使用您的首选项格式,因为您不需要知道样式。 但是,以我的经验,我看到很多使用CAST和CONVERT函数的代码,因此最好了解它们。

Note: For more information about the FORMAT function, refer to this link: FORMAT (Transact-SQL)

注意: 有关FORMAT函数的更多信息,请参考以下链接: FORMAT(Transact-SQL)

与SQL转换日期操作有关的问题 (Problems related to SQL convert date operations)

When you try to convert to date it is not always possible. The following example shows a common error:

当您尝试转换为日期时,并非总是可能。 以下示例显示一个常见错误:

declare @vardate varchar(100)='11242016'
select CONVERT(datetime, @vardate) as dataconverted

The error message is the following:

错误消息如下:

Msg 242, Level 16, State 3, Line 22

消息242,第16级,州3,第22行

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

从varchar数据类型到datetime数据类型的转换导致值超出范围。

You need separators for the date like a “/”, a “.” or a “-“.

您需要用于日期的分隔符,例如“ /”,“。” 或“-”。

The following example, modifies the string from 11242016 to 11-24-2016 and then converts to sql date:

以下示例将字符串从11242016修改为11-24-2016,然后转换为sql date:

declare @vardate varchar(100)='11242016'
 
set @vardate= SUBSTRING(@vardate, 1, 2)+'-'+ SUBSTRING(@vardate, 3, 2)+'-'+SUBSTRING(@vardate, 5, 4)
 
select CONVERT(date, @vardate) as dataconverted

We use substring to concatenate the “-” to use an acceptable date format and then we use the CONVERT function to convert the characters to sql date.

我们使用子字符串来连接“-”以使用可接受的日期格式,然后使用CONVERT函数将字符转换为sql date。

日期数据类型 (Date data types)

In SQL Server, there are several types of date datatypes:

在SQL Server中,有几种类型的日期数据类型:

  • Time returns the hours, minutes, seconds and nanoseconds (hh:mm:ss.nnnnnn)

    时间返回小时,分钟,秒和纳秒(hh:mm:ss.nnnnnn)
  • Date returns the year, months and days (yyyy-mm-dd)

    日期返回年,月和日(yyyy-mm-dd)
  • Datetime returns data with this format: YYYY-MM-DD hh:mm:ss[.nnn]

    日期时间以以下格式返回数据:YYYY-MM-DD hh:mm:ss [.nnn]
  • Smalldatetime returns date with this format: YYYY-MM-DD hh:mm:ss

    Smalldatetime以以下格式返回日期:YYYY-MM-DD hh:mm:ss
  • Datetime2 is similar to Datetime, but it has more precision (YYYY-MM-DD hh:mm:ss[.nnnnnnn])

    Datetime2与Datetime类似,但具有更高的精度(YYYY-MM-DD hh:mm:ss [.nnnnnnn])
  • Datetimeoffset it has the precision of datetime2, but it is used for time zones in UTC

    Datetimeoffset它具有datetime2的精度,但它用于UTC中的时区

SQL将日期转换为整数 (SQL convert date to integer)

If you use the CONVERT or CAST to convert a datetime to integer, it will return the number of days since 1900 until the date provided.

如果使用CONVERT或CAST将日期时间转换为整数,它将返回自1900年到提供的日期为止的天数。

For example, the following T-SQL code will show the number of days from 1900 until today:

例如,以下T-SQL代码将显示从1900到今天的天数:

SELECT CONVERT(INT, GETDATE())

You can also convert to integer the year, months, days, etc. of a datetime value. The following code shows how to store in integer variables the day, month and year of a datetime value:

您还可以将日期时间值的年,月,日等转换为整数。 以下代码显示如何在整数变量中存储日期时间值的日,月和年:

declare @year int = year(getdate())
 
declare @month int = month(getdate())
declare @day int = day(getdate())
select @year as year,@month as month,@day as day

有关SQL Server中SQL转换日期的常见问题 (Common Questions about SQL convert date in SQL Server)

Note: The following link contains FAQ about functions and dates in SQL Server: FAQ about Dates in SQL Server

注意: 以下链接包含有关SQL Server中的功能和日期的 常见问题解答 有关SQL Server中的日期的常见问题解答

结论 (Conclusions)

In this article, we learned how to do a SQL convert date in SQL Server. We learned how to modify the data type in a table, how to use the CAST, CONVERT and FORMAT functions. We also learned about the different types of SQL data types.

在本文中,我们学习了如何在SQL Server中执行SQL转换日期。 我们学习了如何修改表中的数据类型,如何使用CAST,CONVERT和FORMAT函数。 我们还了解了不同类型SQL数据类型。

翻译自: https://www.sqlshack.com/sql-convert-date/

sql日期格式转换函数

你可能感兴趣的:(sql日期格式转换函数_SQL转换日期)