Sunday, 14 June 2020

[SQL Server] TRY_CAST, TRY_CONVERT

[SQL Server] TRY_CAST, TRY_CONVERT

TRY_CAST and TRY_CONVERT are basically the same as CAST and CONVERT. The big difference is that TRY_CAST and TRY_CONVERT return NULL when they fail to CONVERT data type.


TRY_CAST and TRY_CONVERT are the same but different expression the same as CAST and CONVERT.

CONVERT
DECLARE @INPUT VARCHAR(100)

SET @INPUT = '100,2';

SELECT CONVERT(FLOAT,@INPUT) AS INPUT_CONVERT;

Msg 8114, Level 16, State 5, Line 5
Error converting data type varchar to float.



TRY_CONVERT
DECLARE @INPUT VARCHAR(100)

SET @INPUT = '100,2';

SELECT TRY_CONVERT(FLOAT,@INPUT) AS INPUT_CONVERT;



This is also useful when you have to join 2 tables with the different data types and you can ignore unmatched columns.

e.g.

SELECT
 tbl1.Col1,
 tbl2.Col2
FROM
 Table1 tbl1 INNER JOIN Tabl2 tbl2 ON tbl1.ID = TRY_CONVERT(INT,tbl2.KeyID)



No comments:

Post a Comment

(KOR)☁️ AWS Solutions Architect Associate 자격증 취득 여정

  !저의 경험 , 팁 , 그리고 SAA-C03 자격증 합격을 위한 노하우 공유! 조금 늦은 포스팅이지만 , 꼭 공유하고 싶었던 이야기입니다 . 회사 내 주변 동료들이 자주 이렇게 말하곤 했습니다 . “ 님 실...