[ztjSQL]CAST 和 CONVERT

来源:互联网 发布:易语言源码网站 编辑:程序博客网 时间:2022/01/21 23:10
 引:这是sql server 2000帮助文档上的一段,引用到这是觉得哪好,再来提醒自己多看看帮忙文档!
A. 同时使用 CAST 和 CONVERT

每个示例都将检索书名(这些图书的截止当前销售额的第一位数字为 3),并将这些图书的 ytd_sales 转换为 char(20)

-- Use CAST.USE pubsGOSELECT SUBSTRING(title, 1, 30) AS Title, ytd_salesFROM titlesWHERE CAST(ytd_sales AS char(20)) LIKE '3%'GO-- Use CONVERT.USE pubsGOSELECT SUBSTRING(title, 1, 30) AS Title, ytd_salesFROM titlesWHERE CONVERT(char(20), ytd_sales) LIKE '3%'GO

下面是任一查询的结果集:

Title                          ytd_sales   ------------------------------ ----------- Cooking with Computers: Surrep 3876        Computer Phobic AND Non-Phobic 375         Emotional Security: A New Algo 3336        Onions, Leeks, and Garlic: Coo 375         (4 row(s) affected)
B. 使用带有算术运算符的 CAST

下面的示例通过将总的截止当前销售额 (ytd_sales) 与每本图书的价格 (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   ------------------------------------------------------------ ----------- Fifty Years in Buckingham Palace Kitchens                    15096       (1 row(s) affected)