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) AI와 지속 가능한 엔지니어링 — 생성은 빠르게, 검증은 철저하게

영어 원문 : https://www.linkedin.com/pulse/ai-sustainable-engineering-generate-fast-verify-thoroughly-yoon-hclqf/ [공지 / 면책 조항] 이 글에 표현된 모든 견해는 전...