ales) 与每本图书的价格 (price) 相除,进行单独列计算 (Copies)。在四舍五入到最接近的整数后,此结果将转换为 int 数据类型。
USE pubsGOSELECT CAST(ROUND(ytd_sales/price, 0) AS int) AS ''Copies''FROM titlesGO
下面是结果集:
Copies ------ 205 324 6262 205 102 7440 NULL 383 205 NULL 17 187 16 204 418 18 1263 273 (18 row(s) affected)
C. 使用 CAST 进行串联
下面的示例使用 CAST 数据类型转换函数来串联非字符、非二进制表达式。
USE pubsGOSELECT ''The price is '' + CAST(price AS varchar(12))FROM titlesWHERE price > 10.00GO
下面是结果集:
------------------ The price is 19.99 The price is 11.95 The price is 19.99 The price is 19.99 The price is 22.95 The price is 20.00 The price is 21.59 The price is 10.95 The price is 19.99 The price is 20.95 The price is 11.95 The price is 14.99 (12 row(s) affected)
D. 使用 CAST 获得更多易读文本
下面的示例在选择列表中使用 CAST 将 title 列转换为 char(50) 列,这样结果将更加易读。
USE pubsGOSELECT CAST(title AS char(50)), ytd_salesFROM titlesWHERE type = ''trad_cook''GO
下面是结果集:
ytd_sales-------------------------------------------------- ---------Onions, Leeks, and Garlic: Cooking Secrets of the 375Fifty Years in Buckingham Palace Kitchens 15096Sushi, Anyone 4095(3 row(s) affected)
E. 使用带有 LIKE 子句的 CAST
下面的示例将 int 列(ytd_sales 列)转换为 char(20) 列,以便使用 LIKE 子句。
USE pubsGOSELECT title,
-
ytd_salesFROM titlesWHERE CAST(ytd_sales AS char(20)) LIKE ''15%'' AND type = ''trad_cook''GO
下面是结果集:
title ytd_sales ------------------------------------------------------------
Mysql:
MySQL 的CAST()和CONVERT()函数可用来获取一个类型的值,并产生另一个类型的值。两者具体的语法如下:
1
CAST(value as type);
2
CONVERT(value, type);
就是CAST(xxx AS 类型), CONVERT(xxx,类型)。
可以转换的类型是有限制的。这个类型可以是以下值其中的一个:
二进制,同带binary前缀的效果 : BINARY
字符型,可带参数 : CHAR()
日期 : DATE
时间: TIME
日期时间型 : DATETIME
浮点数 : DECIMAL
整数 : SIGNED
无符号整数 : UNSIGNED
下面举几个例子:
例一
1
mysql> SELECTCONVERT('23',SIGNED);
2
+----------------------+
3
| CONVERT('23',SIGNED) |
4
+----------------------+
5
| 23 |
6
+----------------------+
7
1 row inset
例二
1
mysql> SELECTCAST('125e342.83'ASsigned);
2
+------------------------------+
3
| CAST('125e342.83'ASsigned) |
4
+------------------------------+
5
| 125 |
6
+------------------------------+
7
1 row inset
例三
1
mysql> SELECTCAST('3.35'ASsigned);
2
+------------------------+
3
| CAST('3.35'ASsigned) |
4
+------------------------+
5
| 3 |
6
+------------------------+
7
1 row inset
像上面例子一样,将varchar 转为int 用 cast(a as signed),其中a为varchar类型的字符串。
例4
在SQL Server中,下面的代码演示了datetime变量中,仅包含单纯的日期和单纯的时间时,日期存储的十六进制存储表示结果。
01
DECLARE @dt datetime
02
03
--单纯的日期
04
SET @dt='1900-1-2'
05
SELECT CAST(@dt asbinary(8))
06
--结果: 0x0000000100000000
07
08
--单纯的时间
09
SET @dt='00:00:01'
10
SELECT CAST(@dt asbinary(8))
11
--结果: 0x000000000000012C
MySQL的类型转换和SQL Server一样,就是类型参数有点点不同:CAST(xxx AS 类型) , CONVERT(xxx,类型)。