sql語句 型別轉換

2021-06-09 19:23:21 字數 1767 閱讀 4165

簡介:

資料型別轉換可以通過cast()和convert()函式來實現。大多數情況下,這兩個函式是重疊的,它們反映了sql語言的演化歷史。這兩個函式的功能相似,不過它們的語法不同。雖然並非

所有型別的值都能轉變為其他資料型別,但總的來說,任何可以轉換的值都可以用簡單的函式實現轉換。

語法:

cast ( expression as data_type ) 

convert (data_type[(length)], expression [, style])

用例:

a.檢索書名當前銷售額的第一位數字為3,通過將ytd_sales轉換為char(20)實現。 

use   pubs  

go  

select   substring(title,   1,   30)   as   title,   ytd_sales  

from   titles  

where   cast(ytd_sales   as   char(20))   like   '3%'  

gouse   pubs  

go  

select   substring(title,   1,   30)   as   title,   ytd_sales  

from   titles  

where   convert(char(20),   ytd_sales)   like   '3%'   go

b.   使用帶有算術運算子的cast

use   pubs  

go  

select   cast(round(ytd_sales/price,   0)   as   int)   as   'copies'  

from   titles  

go  

c.   使用cast進行串聯

use   pubs  

go  

select   'the   price   is   '   +   cast(price   as   varchar(12))  

from   titles  

where   price   >   10.00  

go  

d.使用cast獲得更多易讀文字  

use   pubs  

go  

select   cast(title   as   char(50)),   ytd_sales  

from   titles  

where   type   =   'trad_cook'  

go

e.使用帶有like子句的cast

use   pubs  

go  

select   title,   ytd_sales  

from   titles  

where   cast(ytd_sales   as   char(20))   like   '15%'  

and   type   =   'trad_cook'  

go  

當從乙個 sql server 物件的資料型別向另乙個轉換時,一些隱性和顯式資料型別轉換是不支援的。例如,nchar 數值根本就不能被轉換成 image 數值。nchar 只能顯式地轉換成 binary,隱性地轉換到 binary 是不支援的。nchar 可以顯式地或者隱性地轉換成 nvarchar。

sql語句型別

左外連線 left outer 右外連線 right outer 全外連線 full outer 交叉連線 cross date format from unixtime queryname 1000 y m d date format from unixtime create time 1000 ...

sql型別轉換

型別轉換 字串和其他型別資料進行拼接元算的時候,需要顯示的把其他型別轉換為字串型別。view code 1 1cast expression as datatype 22 convert datatype expression 3declare name varchar 20 4 declare a...

linq語句 型別轉換

前因 使用linq語句在資料庫中查詢一段時間內的資訊。將表中的資料給實體,尷尬的是表中date這個欄位是string型別,需要轉換。liststarttime from u in dbcontext.t user join a in dbcontext.t addmcoinrecord on u.u...