Wednesday, September 13, 2017
SQL Server TRY_CONVERT returns an error instead of NULL
Tuesday, July 26, 2016
Result shows asterisk when converting int to varchar
See this code;
DECLARE @x int = 1000; DECLARE @y char(2); SET @y = @x; SELECT @y;
When the value 1000 is converted to char(2), the result becomes asterisk because the set data type cannot hold 1000. The asterisk indicates that value is truncated.
Here are some known results when converting to an expression of a different data type.
Saturday, February 8, 2014
TRY Counterparts for CAST, CONVERT and PARSE
For implementing explicit conversion from one type to another, we have been using either CAST or CONVERT functions given by Microsoft SQL Server. CAST is the standard ANSI way of converting and CONVERT is proprietary to Microsoft for converting. SQL Server 2012 introduces another function for converting string to date, time, and number, that accepts an additional argument for culture setting.
In addition to these three functions, CAST, CONVERT and PARSE have their counterparts called TRY_CAST, TRY_CONVERT, and TRY_PARSE. The different between them is, new functions return NULL for conversions with inconvertible input types instead of throwing errors.
Here is an example code;
- DECLARE @input varchar(10) = '1000'
- -- these three SELECTs
- -- return values without
- -- any issue
- SELECT CAST(@input AS money)
- SELECT CONVERT(money, @input)
- SELECT PARSE(@input as money)
- -- change the value
- SET @input = 'Thousand'
- -- these three SELECTs
- -- throw errors
- SELECT CAST(@input AS money)
- SELECT CONVERT(money, @input)
- SELECT PARSE(@input as money)
- -- these three SELECTs
- -- return NULLs
- SELECT TRY_CAST(@input AS money)
- SELECT TRY_CONVERT(money, @input)
- SELECT TRY_PARSE(@input as money)
What should we use? It depends on the way you need to handle it. If you need to continue the execution without any error, TRY_* is the best. However if the execution should be stopped with inconvertible data types, traditional conversion would be the best.