赞
踩
MS SQL Server provides some functions in order to make database administrators’ life easier. A typical database store different types of values. In some cases, we may need to cast and convert these values into different data types. MS SQL provides CAST()
function can be used to change data types.
MS SQL Server提供了一些功能,以使数据库管理员的工作更加轻松。 典型的数据库存储不同类型的值。 在某些情况下,我们可能需要转换这些值并将其转换为不同的数据类型。 MS SQL提供的CAST()
函数可用于更改数据类型。
CAST() function has a simple syntax where we will provide the value and the type we want to cast to.
CAST()函数具有一种简单的语法,其中我们将提供要转换为的值和类型。
CAST(expression AS datatype(length))
expression
is the value, variable, or expression we want to convert.
expression
是我们要转换的值,变量或表达式。
datatype
is the data type we want to convert to.
datatype
是我们要转换为的数据类型。
length
is optional where varchar or similar data types require length for the variable storage.
在varchar或类似数据类型需要变量存储长度的情况下, length
是可选的。
Date and times can be expressed in string format but MS SQL also provides DateTime date type which provides special functions about date and time. In this example, we will provide some data in string format and convert it into MS SQL DateTime format.
日期和时间可以用字符串格式表示,但是MS SQL还提供了DateTime日期类型,该类型提供了有关日期和时间的特殊功能。 在此示例中,我们将以字符串格式提供一些数据并将其转换为MS SQL DateTime格式。
SELECT CAST('2017-08-25 12:05:34.789' AS datetime);
We can see from the screenshot that the date which consists of year, month, day and time which also consist of the hour, minute, second and millisecond converted into datetime
type.
从屏幕截图中我们可以看到,由年,月,日和时间组成的日期也由小时,分钟,秒和毫秒组成,这些datetime
转换为datetime
类型。
In the previous example, we have converted a string into DateTime format which is a compound type for date and time. We can also convert or cast just the string into a date.
在前面的示例中,我们将字符串转换为DateTime格式,这是日期和时间的复合类型。 我们还可以将字符串仅转换或转换为日期。
SELECT CAST('2017-08-25' AS date);
We can also just cast or convert a string into a time which contains hour, minute, second, a millisecond.
我们还可以将字符串强制转换或转换为包含小时,分钟,秒,毫秒的时间。
SELECT CAST('12:13:14.567' AS time);
We can cast a number into a character or character array/string. We will use char
data type in this example but other char types like nchar
, varchar
can be also used.
我们可以将数字转换为字符或字符数组/字符串。 在此示例中,我们将使用char
数据类型,但也可以使用其他char类型,例如nchar
, varchar
。
SELECT CAST( 67 AS char);
We can also provide numbers in string format and convert them into number
data type easily.
我们还可以提供字符串格式的数字,并将其轻松转换为number
数据类型。
SELECT CAST( '123' AS number);
number
data type only stores integers and floating points can not be stored. We can cast a string into a floating-point number with the float
data type.
number
数据类型仅存储整数,不能存储浮点数。 我们可以将字符串转换为具有float
数据类型的float
。
SELECT CAST( '123.456' AS float);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。