CAST 和 CONVERT

来源:互联网 发布:重庆时时彩二星软件 编辑:程序博客网 时间:2024/04/24 16:25

A. 同时使用 CAST 和 CONVERT
每个示例都将检索书名(这些图书的截止当前销售额的第一位数字为 3),并将这些图书的 ytd_sales 转换为 char(20)。

-- Use CAST.
USE pubs
GO
SELECT SUBSTRING(title, 1, 30) AS Title, ytd_sales
FROM titles
WHERE CAST(ytd_sales AS char(20)) LIKE '3%'
GO

-- Use CONVERT.
USE pubs
GO
SELECT SUBSTRING(title, 1, 30) AS Title, ytd_sales
FROM titles
WHERE 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 pubs
GO
SELECT CAST(ROUND(ytd_sales/price, 0) AS int) AS 'Copies'
FROM titles
GO

下面是结果集:

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 pubs
GO
SELECT 'The price is ' + CAST(price AS varchar(12))
FROM titles
WHERE price > 10.00
GO

下面是结果集:

------------------
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 pubs
GO
SELECT CAST(title AS char(50)), ytd_sales
FROM titles
WHERE type = 'trad_cook'
GO

下面是结果集:

                                                       ytd_sales
--------------------------------------------------     ---------
Onions, Leeks, and Garlic: Cooking Secrets of the      375
Fifty Years in Buckingham Palace Kitchens              15096
Sushi, Anyone?                                         4095

(3 row(s) affected)

E. 使用带有 LIKE 子句的 CAST
下面的示例将 int 列(ytd_sales 列)转换为 char(20) 列,以便使用 LIKE 子句。

USE pubs
GO
SELECT title, ytd_sales
FROM titles
WHERE 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)

 

 

原创粉丝点击