SQL Server safely prints a string and fails

declare @input varchar(255) = 'abc'

select * from table where id = CAST(@input as int)

Can I make it so that the cast doesn’t work out quietly or is set to any user-defined default (or system default)?

+5
source share
2 answers

Denali has try_convertand try_parsefunctions.

Until then you can use

DECLARE @input VARCHAR(11) = 'abc'

SELECT * 
FROM table 
WHERE id =  CAST(CASE WHEN @input NOT LIKE '%[^0-9]%' THEN @input END AS INT)

(, int), (, ) CASE, , CASE .

+12

TRY-CATCH CATCH .

+1

All Articles