投
Cast()
函式用於將資料型別變數或資料從一種資料型別轉換為另一種資料型別。
句法
CAST([Expression] AS 資料型別)
要轉換表示式的資料型別是目標型別。要轉換的表示式的資料型別是源型別。
DECLARE @A varchar(2)
DECLARE @B varchar(2)
set @A='25a'
set @B='15'
Select CAST(@A as int) + CAST(@B as int) as Result
--'25a' is casted to 25 (string to int)
--'15' is casted to 15 (string to int)
--Result
--40
DECLARE @C varchar(2) = 'a'
select CAST(@C as int) as Result
--Result
--Conversion failed when converting the varchar value 'a' to data type int.
如果失敗則引發錯誤