在SQL SERVER中,cast和convert函數都可用於類型轉換,其功能是相同的,
只是語法不同.
cast一般更容易使用,convert的優點是可以格式化日期和數值.
1 select CAST('123' as int) -- 123 2 select CONVERT(int, '123') -- 123 3 4 select CAST(123.4 as int) -- 123 5 select CONVERT(int, 123.4) -- 123 6 7 select CAST('123.4' as int) 8 select CONVERT(int, '123.4') 9 -- Conversion failed when converting the varchar value '123.4' to data type int. 10 11 select CAST('123.4' as decimal) -- 123 12 select CONVERT(decimal, '123.4') -- 123 13 14 15 select CAST('123.4' as decimal(9,2)) -- 123.40 16 select CONVERT(decimal(9,2), '123.4') -- 123.40 17 18 19 declare @Num money 20 set @Num = 1234.56 21 select CONVERT(varchar(20), @Num, 0) -- 1234.56 22 select CONVERT(varchar(20), @Num, 1) -- 1,234.56 23 select CONVERT(varchar(20), @Num, 2) -- 1234.5600
在時間轉化中一般用到convert,因為它比cast多加了一個style,可以轉化成不同時間的格式
CONVERT(data_type(length),data_to_be_converted,style)
data_type(length) 規定目標數據類型(帶有可選的長度)。data_to_be_converted 含有需要轉換的值。style 規定日期/時間的輸出格式。
可以使用的 style 值:
1 CONVERT(VARCHAR(19),GETDATE()) 2 CONVERT(VARCHAR(10),GETDATE(),110) 3 CONVERT(VARCHAR(11),GETDATE(),106) 4 CONVERT(VARCHAR(24),GETDATE(),113)